复制构造函数调用
A copy constructor call
>我声明了一个这样的 Point 类:
class Point{
private :
int a,b;
public :
Point(Point const &p) {
a = p.a + 1;
b = 0;
}
Point(){a=2; b=3;}
int getX(){return a;}
int getY(){return b;}
};
int main(){
Point p1,p2;
p2=p1;
cout << p2.getX(); // 2
cout << p2.getY(); // 3
}
为什么不调用复制构造函数?
int main(){
Point p1;
Point p2=p1;
cout << p2.getX(); // 3
cout << p2.getY(); // 0
}
这是复制构造
Point p2=p1; // p2 is constructed here.
// This is shorthand for Point p2(p1);
这是作业
p2=p1; // p2 already exists (it was created on the previous line).
赋值运算符的定义如下:
// If you don't define this the compiler will generate one for you.
Point& operator=(Point const& rhs)
{
// Copy for rhs into this.
return *this;
}
// The compiler generated one looks like this:
Point& operator=(Point const& rhs)
{
a = rhs.a;
b = rhs.b;
return *this;
}
在第一个程序中
int main(){
Point p1,p2;
p2=p1;
^^^^^
有 称为编译器隐式创建的复制赋值运算符。在此程序中,对象p2
已使用默认构造函数创建
Point p1,p2;
在第二个程序中
int main(){
Point p1;
Point p2=p1;
^^^^^^^^^^^
确实有所谓的复制构造函数。
Point p1,p2;
p2=p1;
P2 已经构造,因此第二条语句调用赋值运算符
点 p1;点 p2=p1;
这里 p2 是复制构造的,因为它以前从未被构造过。
请考虑以下代码:
#include <iostream>
class A {
public:
A() { std::cout << "Ctor calledn"; }
A(const A&) { std::cout << "Copy Ctor calledn"; }
A& operator=(const A&) { std::cout << "Assignment operator calledn"; return *this;}
};
int main() {
A a,b;
b = a;
A c;
A d = c;
}
其输出具有启发性:
Argento:Desktop marinos$ clang++ test.cpp -o test
Argento:Desktop marinos$ ./test
Ctor called
Ctor called
Assignment operator called
Ctor called
Copy Ctor called
相关文章:
- 当从函数参数中的临时值调用复制构造函数时
- 为什么调用复制构造函数而不是移动构造函数?
- 为用户定义的类正确调用复制构造函数/赋值运算符
- push_back std::vector,则重复调用复制构造函数
- 减少复制构造函数调用
- 为什么调用复制构造函数来构造空unique_ptr向量?
- 复制elision、std::move和链式函数调用
- 为什么转换运算符调用复制构造函数两次,而等效函数只调用它一次
- 我打算调用initializer_list构造函数,如果存在,则事先调用复制构造函数:为什么?
- 构造函数初始值设定项列表未调用复制构造函数
- 为什么在我的代码中调用复制构造函数而不是移动构造函数?
- std::map 在 [] 上调用默认构造函数,在 insert() 上调用复制构造函数
- 通过引用传递对象时是否调用复制构造函数?
- 如果函数按值传递并按值返回,将调用复制构造函数多少次
- 为什么要抛出引用调用复制构造函数的异常?
- 为什么即使参数标记为"const",也会调用复制构造函数?
- Clang-Tidy:移动构造函数通过调用复制构造函数来初始化类成员
- linux 是否"rename"函数调用块,直到复制(当源和目标在不同磁盘中时)完成
- 为什么当我添加一个不同的对象(复制构造函数中的参数)时调用复制构造函数?
- 为什么调用复制构造函数,当我只返回对象 c++ 的引用时