c++ - 为什么调用简单构造函数后调用复制构造函数?
问题描述
我试图理解复制构造函数,并阅读了这篇(https://www.tutorialspoint.com/cplusplus/cpp_copy_constructor.htm)教程点文章。但是,我无法理解何时在下面的代码中调用了复制构造函数。不只Line line(10)
调用 Simple 构造函数,然后为 ptr 分配内存并将 ptr 的值设置为 10?
是因为我们将 line 作为参数传递给 display 吗?那么将对象作为参数传递是否总是调用复制构造函数?
#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(10) 不只调用 Simple 构造函数吗
是的。
是因为我们将 line 作为参数传递给 display 吗?
是的。
那么将对象作为参数传递是否总是调用复制构造函数?
不必要。例如,某些类型没有构造函数,因此复制它们不会调用构造函数。此外,如果您传递一个右值,则可能会调用移动构造函数。或者,如果实参的类型与形参的类型不同,则可以调用转换构造函数或转换运算符。
如果参数是引用(类型相同,因此不涉及转换),则不调用构造函数。
推荐阅读
- python - 提取数据框中的公共信息
- mybatis - MyBatis resultMap 中是否需要'jdbcType'?
- powershell - 无法通过 Powershell 在 ARM 模板中传递数组类型参数
- scala - 在流中发送 actorRefWithAck
- spring-boot - Spring Boot Maven 插件错误 - 运行时发生异常。空:空指针异常
- laravel - 未找到包中的控制器
- python - 用多种理解填充字典
- mysql - 使用 CSV 从另一个表中的 B 列获取表 A 列中的值
- javascript - 显示加载器 gif,直到在浏览器中开始下载
- postgresql - 执行脚本时,Alter table to enable RLS 在事务中不起作用