如何在构造函数初始化列表中进行深度复制.c++

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

本文关键字:深度 复制 c++ 列表 构造函数 初始化      更新时间:2023-10-16

这是列表类中节点的构造函数。我需要做一个酒厂的深度复制,初始化列表中的另一个类。物品是一个酿酒厂的例子。

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

酿酒厂建设者:

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;
}

在Node ctor中绝对没有复制酒庄三次的原因
一次就足够了:

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

您可以添加一个移动ctor(C++11及更高版本):

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

类似于Winery
如果这四个都是成员,那么Winery-ctor已经进行了深度复制。

我希望你记得第三条规则,还提供了一个自定义的复制操作符、复制赋值操作符和dtor
不过,最好使用std::unique_ptrstd::string

此外,顶级cv限定符是无用的,因此我删除了它们。

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