Mis*_*s94 1 c++ oop constructor c++11
我想知道这个代码如何专门运行第54行(第2行=第1行),尽管赋值运算符没有重载?从输出看来,复制构造函数和普通构造函数都没有被调用,令人惊讶的是它得到了预期的输出199 199
#include <iostream>
using namespace std;
class Line
{
public:
int getLength();
Line( int len ); // simple constructor
Line( const Line &obj); // copy constructor
~Line(); // destructor
private:
int *ptr;
};
Line::Line(int len)
{
cout << "Normal constructor allocating ptr" << endl;
ptr = new int;
*ptr = len;
}
Line::Line(const Line &obj)
{
cout << "Copy constructor allocating ptr." << endl;
ptr = new int;
*ptr = *obj.ptr;
}
Line::~Line(void)
{
cout << "Freeing memory!" << endl;
delete ptr;
}
int Line::getLength()
{
return *ptr;
}
void display(Line obj)
{
cout << "Length of line : " << obj.getLength() <<endl;
}
// Main function for the program
int main()
{
Line line1(199);
Line line2(1);
line2 = line1; // How this is executed ??!
cout << line1.getLength() << " " << line2.getLength() << endl ;
/*display(line1);
display(line2);*/
cin.get();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
你有什么未定义的行为.您已分配line2 = line1但没有用户定义的赋值运算符,因此您使用编译器提供的默认值.默认的只复制所有字段,在您的情况下包括int*.这给你相同的两个副本int*,泄露该值line2先前指向,最终双deleteS中的一个line1原来指向.第二个delete相同的指针,在line1超出范围时发生main(),调用未定义的行为.
如果你有一个释放资源的析构函数,你可能也需要一个赋值运算符.参见规则三:http://en.wikipedia.org/wiki/Rule_of_three_%28C%2B%2B_programming%29
但最好的解决方案是停止使用原始指针.使用智能指针,这个问题首先不会发生,你可以省略你的析构函数.