I have a class whose constructor refers to a constant. This string acts as the name of the object and therefore is needed throughout the life cycle of the class instance.
Now imagine how you can 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;
}
Since the string in proc () is created on the stack and therefore deleted when proc () is completed, what happens to my link to it inside the class instance? I assume that it becomes invalid. Would I be better off storing a copy inside the class? I just want to avoid unnecessarily copying potentially large objects like a string ...
source
share