gpt4 book ai didi

多次调用的C++复制构造函数

转载 作者:行者123 更新时间:2023-11-27 23:59:45 25 4
gpt4 key购买 nike

我试图了解复制构造函数的基础知识并遇到了以下示例。

#include <iostream>

using namespace std;

class Line
{
public:
int getLength() const;
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()
{
cout << "Freeing memory!" << endl;
delete ptr;
}
int Line::getLength() const
{
return *ptr;
}

void display(Line obj)
{
cout << "Length of line : " << obj.getLength() <<endl;
}

// Main function for the program
int main( )
{
Line line1(10);

Line line2 = line1; // This also calls copy constructor

//display(line1);
//display(line2);

return 0;
}

执行时,它会给出以下输出。

Normal constructor allocating ptr
Copy constructor allocating ptr.
Copy constructor allocating ptr.
Length of line : 10
Freeing memory!
Copy constructor allocating ptr.
Length of line : 10
Freeing memory!
Freeing memory!
Freeing memory!

拷贝构造函数只被调用了一次,在Line line2 = line1;中,但是好像拷贝构造函数被调用了两次。所以我评论了display(line1);display(line2); 。之后的输出是这样的。

Normal constructor allocating ptr
Copy constructor allocating ptr.
Freeing memory!
Freeing memory!

所以问题(我不知道我应该称它为问题还是它是 C++ 中的默认标准)与显示函数有关。难道是因为 display() 函数自动创建了其处理对象的拷贝,这就是为什么每个实例都调用复制构造函数两次?请澄清。谢谢。

最佳答案

使用 void display(Line obj),您按值传递对象,因此创建拷贝。

您应该通过 (const) 引用来避免复制:

void display(const Line& obj)

关于多次调用的C++复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40047968/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com