我测试了以下代码:
#include <iostream>
#include <vector>
class foo {
public:
int m_data;
foo(int data) : m_data(data) {
std::cout << "parameterised constructor" << std::endl;
}
foo(const foo &other) : m_data(other.m_data) {
std::cout << "copy constructor" << std::endl;
}
};
main (int argc, char *argv[]) {
std::vector<foo> a(3, foo(3));
std::vector<foo> b(4, foo(4));
//std::vector<foo> b(3, foo(4));
std::cout << "a = b" << std::endl;
a = b;
return 0;
}
我明白了
parameterised constructor
copy constructor
copy constructor
copy constructor
parameterised constructor
copy constructor
copy constructor
copy constructor
copy constructor
a = b
copy constructor
copy constructor
copy constructor
copy constructor
但是,如果我用复制构造函数替换std::vector<foo> b(4, foo(4));
,std::vector<foo> b(3, foo(4));
则不会调用,a = b
输出为
parameterised constructor
copy constructor
copy constructor
copy constructor
parameterised constructor
copy constructor
copy constructor
copy constructor
a = b
为什么在这种情况下不调用复制构造函数?
我正在使用 g++ (Ubuntu/Linaro 4.6.1-9ubuntu3) 4.6.1