如何在构造函数初始化列表中进行深层复制。 c ++ [英] How do I make a deep copy in a constructors initialization list. c++
问题描述
这是list类中的节点的构造函数。我需要做一个深的副本的酒厂,在初始化列表中的其他类。 Item是一个酿酒厂的实例。
List :: Node :: Node(const Winery& winery):
(winery)
//你的初始化列表here
{
Winery w = winery;
item = w;
}
酿酒厂的构造函数:
Winery :: Winery(const char * const name,const char * const location,
const int acres,const int rating):
name ,
location(location),
acres(acres),
rating(rating)
{
char * nm = new char [strlen(name) ;
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
>
我希望你记得规则3,并提供了一个自定义的copy-ctor,copy-assignment-operator和dtor。
仍然,更好使用 std :: unique_ptr
或 std :: string
。
此外,顶级cv限定符是无用的,因此我删除了它们。
Winery :: Winery(const char * name,const char * location,
int acres,int rating):
name(strcpy(new char [strlen 1],name),
位置(strcpy(new char [strlen(location)+1],location),
acres(acres),
rating }
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;
}
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)
{}
这篇关于如何在构造函数初始化列表中进行深层复制。 c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!