C++ 如何在构造函数初始化列表中创建深度副本。c++;
这是list类中节点的构造函数。我需要制作winery的深层副本,初始化列表中的另一个类。这是一个酿酒厂的例子C++ 如何在构造函数初始化列表中创建深度副本。c++;,c++,constructor,linked-list,initialization-list,C++,Constructor,Linked List,Initialization List,这是list类中节点的构造函数。我需要制作winery的深层副本,初始化列表中的另一个类。这是一个酿酒厂的例子 List::Node::Node(const Winery& winery) : item(winery) // your initialization list here { Winery w = winery; item = w; } 酿酒厂建造师: Winery::Winery(const char * const name, cons
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;
}
绝对没有理由在节点中复制酿酒厂三次。
一次就够了:
List::Node::Node(const Winery& winery) : item(winery) {}
您可以添加一个移动计算器(C++11及更高版本):
与酿酒厂类似如果这四个人都是成员,
Winery
-ctor已经进行了深度复制
我希望您记住3的规则,并且还提供了一个自定义复制ctor、复制分配运算符和dtor。不过,最好还是使用or 此外,顶级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)
{}
为酿酒厂制作一个ctor,它可以制作一个深度副本。顺便说一句:ctor init列表和ctor主体看起来像是相互复制的。你说得对,我把它去掉。我添加了winery构造函数的代码。“深度复制”和“浅层复制”通常只在仅GC语言中使用,不直接支持值(而不是只支持指针)。您似乎在winery-ctor中重复了这一点。此外,考虑在一些<代码> STD::UnQuyJPPT/<代码> S中为异常安全和EASER清理(希望您有一个Dor,拷贝cTor,以及AssigPuffice操作符也定义了……)。如果<代码>酒厂< /代码>只有4个成员,那么你就已经在那里做了一个深度拷贝。C++中常用的是O11C“浅”VS“深”拷贝。值通常包装分配,根据情况,您可以复制也可以不复制。初始化列表是否使用深度复制?如果我从外部修改winery,则项目将更改?@LiTaiji ctor init列表将使用您给定的表达式初始化元素。这是否意味着深度复制取决于成员。顺便说一句:使用ctor init list来消除初始值设定项_list和大括号init list之间的歧义,它们是不同的东西。也就是说,对于不提供复制构造函数的类的实例,ctor init list使用浅复制。
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)
{}