How do I make a deep copy in a constructors initialization list. c++

最后都变了- 提交于 2019-12-08 06:42:33

问题


This is the constructor for node in list class. I need to make a deep copy of winery, an other class in the initialization list. Item is an instance of winery.

List::Node::Node(const Winery& winery) : 
    item(winery)
    // your initialization list here
{
    Winery w = winery;
    item = w;
}

constructor for winery:

Winery::Winery(const char * const name, const char * const location,
        const int acres, const int rating) :
    name(name),
    location(location),
    acres(acres),
    rating(rating)
{
    char    *nm = new char[strlen(name) + 1];
    char    *loc = new char[strlen(location) + 1];
    strcpy(nm, this->name);
    strcpy(loc, this->location);
    this->name = nm;
    this->location = loc;
    this->acres = acres;
    this->rating = rating;
}

回答1:


There's absolutely no reson to copy the winery three times in the Node-ctor.
Once is enough:

List::Node::Node(const Winery& winery) : item(winery) {}

You might add a move-ctor though (C++11 and later):

List::Node::Node(Winery&& winery) : item(std::move(winery)) {}

Similar for Winery.
If those four are all the members, the Winery-ctor already does a deep-copy.

I hope you remembered the rule-of-3 and also provided a custom copy-ctor, copy-assignment-operator and dtor.
Still, better would be using std::unique_ptr or std::string.

Also, the top-level cv-qualifiers are useless, thus I removed them.

Winery::Winery(const char * name, const char * location,
        int acres, int rating) :
    name(strcpy(new char[strlen(name)+1], name),
    location(strcpy(new char[strlen(location)+1], location),
    acres(acres),
    rating(rating)
{}


来源:https://stackoverflow.com/questions/26310837/how-do-i-make-a-deep-copy-in-a-constructors-initialization-list-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!