如何在构造函数初始化列表中进行深度复制.c++
How do I make a deep copy in a constructors initialization 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;
}
在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_ptr
或std::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)
{}
相关文章:
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- C++尝试深度复制唯一指针时出现内存访问冲突
- 在 c++ 中使用深度复制的运算符重载
- 如何深度复制链表对象指针
- 我有两棵二叉树.我想在不更改输入树的情况下深度复制两个二叉树的结果
- 如何将结构深度复制到向量的每个元素
- 我需要做一个深度复制,我是否正确使用了我的复制构造函数?
- 是否可以在不显式迭代每个元素的情况下深度复制指针容器?
- 如何深度复制unique_ptr向量
- 二叉搜索树 深度复制和取消引用
- 链表的这个别名运算符是否会产生深度复制
- 有没有一种 stl 方法来执行指针向量的深度复制
- cv::P oint3f 赋值运算符是否执行"深度"复制?
- Qt:通过深度复制访问列表中的数据结构是否应该比通过指针访问它慢得多
- 深度复制包含引用成员(C++)的结构
- 如何将“char *”深度复制到std::stringstream
- 如何在双向链表上执行深度复制
- 在复制构造函数中执行深度复制
- 深度复制cv::垫子替代品,哪个更好?
- 在 C/C++ 中使用 ProtoBuf 进行深度复制