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) {}
};
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...