user3027198 user3027198 - 1 year ago 57
C++ Question

Why would I want to use reference to const in Constructor?

A bit silly question but Why?

Why would I want to use reference to const string, instead of just declaring a local string in Constructor?

class Person (const string &first_name, const string &last_name);
class Person (string first_name, string last_name);


Am I getting a reference to an automatic variable that way? o_O

Thank you!

Answer Source

Because the semantics of what happens "behind the scenes" are quite different.

class Person1 {
    std::string f_name, l_name;
public:
    Person(std::string first_name, std::string last_name) :
    f_name(first_name), l_name(last_name) {
    }
};

class Person2 {
    std::string f_name, l_name;
public:
    Person(const std::string & first_name, const std::string & last_name) :
    f_name(first_name), l_name(last_name) {
    }
};

When you construct an instance of Person1, the names used to initialize it get copied twice: first to initiate local variables in the constructor, and second to copy-construct to the member variables. With Person2, however, only one copy happens: when the copy-construct to the member variables occurs.

With a trivial example like this, it might not be clear that this represents significant performance and memory implications, but for more complex programs, this can be quite significant.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download