提问人:Amir reza Riahi 提问时间:8/5/2022 更新时间:8/5/2022 访问量:77
为什么复制构造函数在这里被调用两次?[复制]
Why is the copy constructor called twice here? [duplicate]
问:
我的代码是这样的:
#include <vector>
#include <iostream>
class A{
public:
A() = default;
A(const A& obj){
std::cout << "Copy c-tor" << std::endl;
}
A(A&& obj){
std::cout << "Move c-tor" << std::endl;
}
};
int main(int argc, char *argv[]){
std::vector<A> vA;
std::cout << "Copy ctor will be invoked: " << std::endl;
auto a = A();
vA.push_back(a);
std::cout << "Move ctor will be invoked: " << std::endl;
vA.push_back(A());
return 0;
}
我期望有一个复制构造函数调用和一个移动构造函数调用。但输出有一个 two copy 构造函数调用。原来如此:
[amirreza@localhost copy]$ g++ copy.cpp
[amirreza@localhost copy]$ ./a.out
Copy ctor will be invoked:
Copy c-tor
Move ctor will be invoked:
Move c-tor
Copy c-tor
为什么上次叫复制ctor?为什么复制构造函数被调用两次?
答: 暂无答案
评论
reserve