Could anyone explain me the reason why is in this code defined MyClass ( const MyClass & src ) { m_X = src . m_X; }
? Without this line of code it works fine as well and gives the same output which is 32
in this case. What's the difference between having it in and not? I read that copy constructor is made automatically but when you have defined pointer in the class you should define it but i don't get why in this case.
Code below:
#include <iostream>
using namespace std;
class MyClass
{
public:
MyClass ( int x ) : m_X ( new int ( x ) ) {}
MyClass ( const MyClass &src )
{
m_X = src.m_X;
}
void print ( void ) const
{
cout << *m_X;
}
private:
int * m_X;
};
int main ( void )
{
MyClass a ( 32 ), c = a;
c.print ();
return 0;
}
答案 0 :(得分:2)
默认的复制构造函数以及复制构造函数执行成员明智的复制(或浅复制)。在这种情况下,您有一个指针,其值是数据所在的地址。这解决了复制的内容。
正如其他帖子所述,您需要更好地管理指针。
答案 1 :(得分:2)
编译器生成一个(和你的)的问题是它复制指针。您现在有两个指针c.m_x
和a.m_x
都指向同一个堆分配的对象。谁拥有它?如果你删除a会发生什么,它应该删除它分配的内存(你错误地不这样做),但是c仍然在蠢蠢欲动。
出于这个原因,有std::shared_ptr
。它专为这种情况而设计,它执行Right Thing By Magic
将int * m_X
替换为std::shared_ptr<int> m_X
答案 2 :(得分:1)
The reason you get the same output is you are doing a shallow copy just like the compiler would do. It is not enough just to copy a pointer. You need to create a new pointer and then set its value to be a copy of what you are copying from. A proper constructor would look like
MyClass ( const MyClass & src ) : m_X(new int(*src.m_X) {}
Now the copy has its own independent pointer that has the same value.
Also note that you need a destructor to delete the memory and a proper copy assignment operator as the default copy assignment operator will do the same thing as the default copy constructor.