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

标签 c++ copy-constructor

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

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/

相关文章:

c++ - Boost TCP 客户端连接多个服务器

c++ - 如何修复主函数在传递参数时调用不正确的函数? (c++)

c++ - 带有工厂设计尝试的段错误 unique_ptr

c++ - 在unix中获取本地时间的最快方法

c++ - 将右值绑定(bind)到左值引用

C++ 复制构造函数 vs 重载赋值 vs 构造函数最佳实践?

c++ - 请求从 'std::string' 到非标量类型的转换

c++ - 基类复制构造函数的可见性问题

c++ - 按住屏幕接受方向键

c++ - 如何在 std::function 中捕获 unique_ptr