即使没有任何要复制的对象,是否会自动调用复制构造函数?
is copy constructor called automatically even when there isn't any object to be copied?
我在网上找到了这件代码:
#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!
我不明白为什么没有作为复制构造函数的参数传递的对象,为什么要调用复制构造函数?另外,在调试时,我了解函数主完成功能后被调用。为什么称呼它,以及为什么在函数主终止后被调用?谢谢,
void display(Line obj) {
此功能按值采用其参数。这意味着将此参数传递给此功能将复制它。当main()
调用display()
。
如果您更改此功能,以便通过参考来采用其参数:
void display(Line &obj) {
您会发现复制构造函数不再从您的示例程序中调用。
您将在C 书中找到有关按值与参考的传递参数的更多信息。
函数显示按值将其参数取值,因此调用复制构造函数。如果不想要,请通过参考 - 线&amp;OBJ。更好的是,按照const参考 - const行&amp;OBJ。但是在后一种情况下,您在显示内部的成员函数也必须是const。
display()
中的参数:
void display(Line obj)
调用复制构造函数,因为在函数的参数中正在制作一个新对象。因此,将您传递给此功能的类Line
的任何对象都将被复制并用作功能主体的过度。
您在以下行中调用此功能:
display(line);
因此,line
的副本是在display()
中制作的。为避免这种情况,请参考Line
类的对象。将参数在函数标题中传递的方式更改为:
void display(Line &obj)
以这种方式,您仅引用对象,因此,不做副本。因此,复制构造函数不会在此处调用。
相关文章:
- 是否可以初始化不可复制类型的成员变量(或基类)
- 当有分配器意识的容器被复制/移动时,反弹分配器是否被复制/移走
- C++矢量复制构造函数和赋值运算符是否也复制保留空间?
- 将对象的字节复制到数组并再次复制回来是否安全
- 是否可以将不可复制的成员用作使对象不可复制的替代方法?
- 是否可以/希望创建不可复制的共享指针模拟(以启用weak_ptr跟踪/借用类型语义)?
- 如果这不是类的"复制构造函数",是否可以移动对象?
- 在这种情况下,使用 string_view 是否会导致不必要的字符串复制?
- 为什么复制构造函数不需要检查输入对象是否指向自身?
- 除了 std::vector 之外,是否有一个 std 容器不会复制和销毁作为类的元素?
- 如果我在块中编写字符串文字,是否会从数据部分复制整个字符串数据?
- 如果我也使用复制构造函数并且重载 = 运算符,我是否需要析构函数?
- 是否可以避免在以下代码中复制/移动构造函数的需要?
- std::vector 是否有用于引用的复制构造函数?
- 通过默认复制构造函数比较 C++ 字符串是否会影响性能,原因为何?
- 访问从联合与另一个成员集复制的联合中的一个成员是否未定义或未指定?
- 通过引用传递是否涉及复制地址
- 如何检查文件复制和写入是否成功
- 字符串是否在其构造函数中复制数据
- 内存C++复制是否将内存地址复制到另一个阵列