我在网上找到了这段代码:
#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!
我不明白为什么在没有对象作为参数传递给复制构造函数时调用复制构造函数? 另外,在调试时,我了解到在函数 main 完成后调用了析构函数。为什么调用它以及为什么在函数 main 终止后调用它? 谢谢,
最佳答案
void display(Line obj) {
此函数按值获取其参数。这意味着将此参数传递给此函数将复制它。当 main()
调用 display()
时,这是调用复制构造函数的地方。
如果您更改此函数,使其通过引用获取其参数:
void display(Line &obj) {
您会发现您的示例程序不再调用复制构造函数。
您会在 C++ 书籍中找到有关按值传递参数与按引用传递参数的更多信息。
关于c++ - 即使没有要复制的对象,复制构造函数也会自动调用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42789311/