我对复制构造函数概念有疑问。我写了一个这样的例子:
struct f1
{
string x;
string y;
f1();
~f1();
};
struct f2
{
int a;
string b;
f1 *ff;
f2();
~f2();
};
class myclass{
f2 *obj;
}
我发现 struct f2 应该有一个复制构造函数,因为该类包含指向已分配内存的指针。但我不知道应该如何创建它。
最佳答案
你有很多选择:
主要两个:
只是复制指针(浅复制),只是不写构造函数,它将是隐式的,或者你可以写(在
struct f2
中)。f2(const f2 &original): f1(original.f1), a(original.a), b(original.b) { }
WARNING: This will NOT copy the value of
f1
member variable. It will just copy the reference, this makes bothf2.f1
s refer to samef1
object.f2 a; ... f2 b(a); // Invokes the "copy" constructor a.f1->x = "Something here"; std::cout << b.f1->x; // Will print "Something here"
做一个深拷贝,调用
f1
的拷贝构造函数,将新创建的拷贝赋值给this->f1
,方法是将this写入>结构 f2
f2(const f2 &original): f1(new f1(*original.f1)), a(original.a), b(original.b) { }
另外正如一位评论者所建议的那样,您必须也进行复制赋值,因为您创建了一个复制构造函数(除非您的对象是不可变的)
f2 &operator=(const f2 &other) { if (this == &other) return; // If "self-assignment" just return. if (f1) { delete f1; } // Deletes the old one if any. // The advisable alternative is to use // a smart pointer f1 = new f1(*other.f1); a = other.a; b = other.b; return *this; }
无论如何,您应该考虑使用智能指针:unique_ptr
、shared_ptr
和weak_ptr
,因为原始指针可能导致很多错误。但是智能指针(部分)为您管理内存,让您有更多机会思考您的逻辑。一些现代 C++ 程序员说你应该很少使用 delete
,智能指针会完成这项工作
关于c++ - 当类包含指针时如何创建复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48840028/