我测试了以下代码:
#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
答案 0 :(得分:12)
在第一种情况下,a
在分配时需要增长,这意味着必须重新分配所有元素(因此需要对其进行破坏和构造)。
在第二种情况下,a
不需要增长,因此使用赋值运算符。
见http://ideone.com/atPt9;添加一个打印消息的重载复制赋值运算符,我们得到以下第二个示例:
parameterised constructor
copy constructor
copy constructor
copy constructor
parameterised constructor
copy constructor
copy constructor
copy constructor
a = b
copy assignment
copy assignment
copy assignment
答案 1 :(得分:3)
正在使用赋值运算符。
#include <iostream>
#include <vector>
class foo {
public:
int m_data;
foo(int data) : m_data(data) {
std::cout << "parameterised constructor " << m_data << std::endl;
}
foo(const foo &other) : m_data(other.m_data) {
std::cout << "copy constructor " << m_data << " " << other.m_data << std::endl;
}
foo& operator= (const foo& other){
std::cout << "assignment operator " << m_data << " " << other.m_data << 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;
for(std::vector<foo>::const_iterator it = a.begin(); it != a.end(); ++it){
std::cout << "a " << it->m_data << std::endl;
}
for(std::vector<foo>::const_iterator it = b.begin(); it != b.end(); ++it){
std::cout << "b " << it->m_data << std::endl;
}
return 0;
}
parameterised constructor 3
copy constructor 3 3
copy constructor 3 3
copy constructor 3 3
parameterised constructor 4
copy constructor 4 4
copy constructor 4 4
copy constructor 4 4
a = b
assignment operator 3 4
assignment operator 3 4
assignment operator 3 4
a 3
a 3
a 3
b 4
b 4
b 4
请参阅Olis回答原因。