C++ references

Assigning reference return value to a variable

When assigning a reference return value to a variable, a copy is made. Here is an example:

class References {
private:
    std::string name;

public:
    References(const std::string& name) : name(name) {
    };

    virtual ~References() {
    };

    const std::string& getName() const {
        return name;
    };
};

References r("foo");
std::string n = r.getName();

This code makes a copy of the name member variable from the References class and puts the copy into the variable n.

Assigning reference return value to a reference variable

When assigning a reference return value to a reference variable, no copy is made. Here is an example:

class References {
private:
    std::string name;

public:
    References(const std::string& name) : name(name) {
    };

    virtual ~References() {
    };

    const std::string& getName() const {
        return name;
    };
};

References r("foo");
const std::string& n = r.getName();

This code does not make a copy of the name member variable. Instead, the reference variable is now a reference directly to the member variable inside the class.

Passing a reference return value to a method that takes a reference

When you pass the return value from a method that returns a reference directly into a method that takes a reference, no copy is made. Here is an example:

class References {
private:
    std::string name;

public:
    References(const std::string& name) : name(name) {
    };

    virtual ~References() {
    };

    const std::string& getName() const {
        return name;
    };
};

void print(const std::string& s) {
    ...;
}

References r("foo");
print(r.getName());

This passes the reference returned directly into the method as a reference. Therefore, no copy is made.

Using a reference method in a comparison operator

This is the same as the method invocation example above because all operators take references.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s