C ++ link in constructor

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 ...

+2
source share
7 answers

, . , myclass.

+8

: . "std::string name" . .

+3

myclass:: _ name , .

+1

. std::string name (not reference) myclass ( - ). const char * . .

class myclass {
public:
    std::string name;
    myclass(const char *_name) : name(_name) { }
};

myclass *proc() {
    return new myclass("hello");
}
+1

std::string , ​​ c str "hello" , .

. c str std: string staic.

+1

myclass:: name std::string. ++ (http://en.wikipedia.org/wiki/Copy-on-write), .

0

Save a copy of the string in MyClass, leaving the link permanently unsafe. If you expect multiple instances to have the same name, you should consider the Flyweight design template , which allows you to store storage when you have many equal instances. Boost.Flyweight is a very convenient implementation of this template, which allows you to simply write:

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

Some std :: string implementations may do this behind the scenes, but this is not required. Therefore, you should not rely on this.

0
source

All Articles