带有赋值运算符的类的C++深度复制
C++ Deep-copy of a class with assignment operator
如果我有一个重载的赋值运算符,需要深度复制一个类,我该怎么做?类Person包含一个Name类
Person& Person::operator=(Person& per){
if (this==&per){return *this;}
// my attempt at making a deep-copy but it crashes
this->name = *new Name(per.name);
}
在名称类中复制构造函数和赋值运算符
Name::Name(Name& name){
if(name.firstName){
firstName = new char [strlen(name.firstName)+1];
strcpy(firstName,name.firstName);
}
Name& Name::operator=(Name& newName){
if(this==&newName){return *this;}
if(newName.firstName){
firstName = new char [strlen(newName.firstName)+1];
strcpy(firstName,newName.firstName);
return *this;
}
我将利用现有的复制构造函数、析构函数和添加的swap()
函数:
Name& Name::operator= (Name other) {
this->swap(other);
return *this;
}
我正在执行的所有复制作业看起来都像这个实现。缺少的swap()
函数对编写来说也是微不足道的:
void Name::swap(Name& other) {
std::swap(this->firstName, other.firstName);
}
对于CCD_ 3也是如此。
相关文章:
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- C++尝试深度复制唯一指针时出现内存访问冲突
- 在 c++ 中使用深度复制的运算符重载
- 如何深度复制链表对象指针
- 我有两棵二叉树.我想在不更改输入树的情况下深度复制两个二叉树的结果
- 如何将结构深度复制到向量的每个元素
- 我需要做一个深度复制,我是否正确使用了我的复制构造函数?
- 是否可以在不显式迭代每个元素的情况下深度复制指针容器?
- 如何深度复制unique_ptr向量
- 二叉搜索树 深度复制和取消引用
- 链表的这个别名运算符是否会产生深度复制
- 有没有一种 stl 方法来执行指针向量的深度复制
- cv::P oint3f 赋值运算符是否执行"深度"复制?
- Qt:通过深度复制访问列表中的数据结构是否应该比通过指针访问它慢得多
- 深度复制包含引用成员(C++)的结构
- 如何将“char *”深度复制到std::stringstream
- 如何在双向链表上执行深度复制
- 在复制构造函数中执行深度复制
- 深度复制cv::垫子替代品,哪个更好?
- 在 C/C++ 中使用 ProtoBuf 进行深度复制