【发布时间】:2023-04-05 22:36:01
【问题描述】:
复制构造函数用于许多事情,例如当我需要使用指针或为对象动态分配内存时。但是在tutorialpoint.com看这个例子:
#include <iostream>
using namespace std;
class Line
{
public:
int getLength( void );
Line( int len ); // simple constructor
Line( const Line &obj); // copy constructor
~Line(); // destructor
private:
int *ptr;
};
// Member functions definitions including constructor
Line::Line(int len)
{
cout << "Normal constructor allocating ptr" << endl;
// allocate memory for the pointer;
ptr = new int;
*ptr = len;
}
Line::Line(const Line &obj)
{
cout << "Copy constructor allocating ptr." << endl;
ptr = new int;
*ptr = *obj.ptr; // copy the value
}
Line::~Line(void)
{
cout << "Freeing memory!" << endl;
delete ptr;
}
int Line::getLength( void )
{
return *ptr;
}
void display(Line obj)
{
cout << "Length of line : " << obj.getLength() <<endl;
}
// Main function for the program
int main( )
{
Line line(10);
display(line);
return 0;
}
结果是:
Normal constructor allocating ptr
Copy constructor allocating ptr.
Length of line : 10
Freeing memory!
Freeing memory!
当我注释掉(复制构造函数)和析构函数中的代码时,我得到了相同的结果:
Normal constructor allocating ptr
Length of line : 10
那么这里使用复制构造函数有什么区别呢?还有为什么“释放内存!”出现两次?
【问题讨论】:
-
查看结果。在第一个示例中,您分配了两个不同的整数并释放它们。在第二种情况下,您分配一个并释放它两次。不好。
-
它在第二个例子中没有被释放,我只是忘记在构造函数中注释“cout
-
那么你分配了一些你没有释放的东西,如果它开始变得比仅仅创建一个并结束程序更复杂,那就是内存泄漏。
-
我知道@chris,但我只是想了解这个概念并知道使用构造函数与不使用构造函数有什么区别?..
-
您可以通过Rule of Three 找到一些很好的参考资料,这些参考资料现在可以被认为是五规则、四半规则或零规则。零的一个例子是使用
std::unique_ptr<int>而不是int *。那么就无需担心析构函数或复制构造函数(或赋值运算符,或移动构造函数/赋值运算符)。
标签: c++ oop copy-constructor