gpt4 book ai didi

c++ - 当类包含指针时如何创建复制构造函数

转载 作者:太空宇宙 更新时间:2023-11-04 14:33:16 25 4
gpt4 key购买 nike

我对复制构造函数概念有疑问。我写了一个这样的例子:

struct f1
{
string x;
string y;
f1();
~f1();
};
struct f2
{
int a;
string b;
f1 *ff;
f2();
~f2();
};
class myclass{
f2 *obj;
}

我发现 struct f2 应该有一个复制构造函数,因为该类包含指向已分配内存的指针。但我不知道应该如何创建它。

最佳答案

你有很多选择:

主要两个:

  1. 只是复制指针(浅复制),只是不写构造函数,它将是隐式的,或者你可以写(在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 both f2.f1 s refer to same f1 object.

f2 a;
...
f2 b(a); // Invokes the "copy" constructor
a.f1->x = "Something here";
std::cout << b.f1->x; // Will print "Something here"
  1. 做一个深拷贝,调用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_ptrshared_ptrweak_ptr,因为原始指针可能导致很多错误。但是智能指针(部分)为您管理内存,让您有更多机会思考您的逻辑。一些现代 C++ 程序员说你应该很少使用 delete,智能指针会完成这项工作

关于c++ - 当类包含指针时如何创建复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48840028/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com