gpt4 book ai didi

c++ - 为什么在这个例子中调用了复制构造函数?

转载 作者:太空狗 更新时间:2023-10-29 23:39:12 25 4
gpt4 key购买 nike

我是 C++ 的新手,我不明白为什么在以下代码中调用了复制构造函数:

 #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!

为什么它在第一个 Line 对象之后用简单的构造函数构造另一个 Line 对象?

谢谢!

最佳答案

因为您将 Line 作为值传递

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

您应该将其作为常量引用传递,这样速度更快(display 应该是常量方法,以便常量对象可以调用它)。

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

(前提是你改成int getLength( void ) const;)

在你的情况下,考虑重新定义赋值运算符

Line &operator=(const Line &other);

或影响另一行中的一行将复制指针数据,并会在您第二次删除对象时崩溃,因为内存将被释放两次。

如果你想确保不能调用默认的复制构造函数/赋值运算符,只需在你的私有(private)部分声明它们:

private:
Line &operator=(const Line &other);
Line(const Line &other);

尝试使用它们的代码将无法编译。

关于c++ - 为什么在这个例子中调用了复制构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39259232/

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