2014-10-11 51 views
1

这是list类中节点的构造函数。我需要在初始化列表中创建一个酒庄的深层副本,另一个类。项目是酿酒厂的一个实例。如何在构造函数初始化列表中进行深层复制。 C++

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

为'winery'制作一个ctor,它可以进行深度复制。顺便说一句:ctor-init-list和ctor-body看起来像重复其他工作。 – Deduplicator 2014-10-11 03:50:01

+0

你说得对,我会把它说出来。我添加了我对酿酒厂构造函数的代码。 – 2014-10-11 03:55:55

+0

“深层复制”与“浅层复制”通常只用于仅支持GC的语言,而不直接支持值(而不仅仅是指针)。 – o11c 2014-10-11 04:06:47

回答

2

绝对没有振振有辞到三倍复制酒厂的节点构造函数。
一次就够了:

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

你可能会增加,虽然一招 - 构造函数(C++ 11及更高版本):

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

类似的Winery
如果这四个都是成员,则Winery -ctor已经做了深度复制。

我希望你记住3的规则,并且还提供了一个自定义的copy-ctor,copy-assignment-operator和dtor。
不过,最好使用std::unique_ptrstd::string

此外,顶级cv-qualifiers是无用的,因此我删除了它们。

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) 
{} 
相关问题