【问题标题】:Copy constructor C++ does not copy pointer correctly复制构造函数 C++ 没有正确复制指针
【发布时间】:2020-07-02 19:55:08
【问题描述】:

我为我的班级创建了一个复制构造函数。有谁知道为什么l1.ptrl2.ptr 在编译后给我相同的地址?做过很多次了,不知道哪里出错了。

#include<iostream>
#include<string>

using namespace std;

class numb
{
public:
    int* ptr;
    numb(int = 3);
    numb(const numb&);
    virtual ~numb();
};

numb::numb(int x)
{
    this->ptr = new int(x);
}

numb::numb(const numb& l1)
{
    this->ptr = new int(*(l1.ptr));

}

numb::~numb()
{    
}

int main()
{
    numb l1(5), l2;
    l1 = l2;
    cout << l1.ptr << endl;
    cout << l2.ptr << endl;
    system("Pause");
    return 0;
}

【问题讨论】:

  • 您忘记提供复制赋值运算符(numb&amp; operator=(numb const&amp;),阅读CppCoreGuidelines
  • 复制结构类似于numb l2 = l1;。使用l2 = l1;,您可以复制 assignment
  • 记住rule of five。您缺少副本分配:operator=()
  • 这只是出于好奇,还是你真的有这样的代码?那为什么是指针呢?您尝试通过使用指向单个int 的指针来解决的实际问题是什么?即使你有数组,为什么要使用指针和手动内存管理而不是std::vector?请了解the rules of three, five and zero。我强烈推荐零规则。
  • 你的意思是l2 = l1,不是l1 = l2,对吧?

标签: c++ class constructor copy


【解决方案1】:

在这个sn-p中:

numb l1(5), l2;
l2 = l1;

第二行没有调用复制构造函数。相反,它正在调用复制赋值运算符。由于您尚未定义,因此您会得到一个浅拷贝。

您可以使用复制构造函数,如下所示:

numb l1(5);
numb l2(l1);

或为您的班级定义operator=

numb& operator=(const numb&);  // do a deep copy

【讨论】:

  • 也没有有用的默认构造函数,所以 OP 可能 意味着 l2 = l1 而不是 l1 = l2
  • @AsteroidsWithWings 哎呀,好消息。已编辑,谢谢。
【解决方案2】:

通过不提供赋值运算符,您将获得编译器为您生成的运算符。编译器确实是在“复制指针”(通常称为“浅拷贝”)。

如果您需要复制pointee(通常称为“深拷贝”),那么您必须实现自己的赋值运算符。

【讨论】:

    猜你喜欢
    • 2016-04-13
    • 1970-01-01
    • 1970-01-01
    • 2016-04-08
    • 1970-01-01
    • 2010-10-21
    • 2011-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多