Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ reference in constructor

I have a class whose constructor takes a const reference to a string. This string acts as the name of the object and therefore is needed throughout the lifetime of an instance of the class.

Now imagine how one could use this class:

class myclass {
public:
    myclass(const std::string& _name) : name(_name) {}
private:
    std::string name;
};

myclass* proc() {
    std::string str("hello");
    myclass* instance = new myclass(str);
    //...
    return instance;
}

int main() {
    myclass* inst = proc();
    //...
    delete inst;
    return 0;
}

As the string in proc() is created on the stack and therefore is deleted when proc() finishes, what happens with my reference to it inside the class instance? My guess is that it becomes invalid. Would I be better off to keep a copy inside the class? I just want to avoid any unneccessary copying of potentially big objects like a string...

like image 498
Milan Avatar asked Jul 10 '26 12:07

Milan


2 Answers

Yes, Reference becomes invalid in your case. Since you are using the string it is better to keep a copy of the string object in myclass class.

like image 149
aJ. Avatar answered Jul 12 '26 01:07

aJ.


By all means: copy. Have a "std::string name" member in your class. It's the only way to control the life-time.

like image 26
stefaanv Avatar answered Jul 12 '26 02:07

stefaanv