Tôi đã thử nghiệm đoạn mã sau:Trong đó trường hợp là các nhà xây dựng bản sao gọi là, nếu một container được sao chép
#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;
}
tôi nhận được
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
Tuy nhiên, nếu tôi thay std::vector<foo> b(4, foo(4));
bởi std::vector<foo> b(3, foo(4));
constructor sao chép không được gọi bởi a = b
và đầu ra là
parameterised constructor
copy constructor
copy constructor
copy constructor
parameterised constructor
copy constructor
copy constructor
copy constructor
a = b
Tại sao trong trường hợp này, trình tạo bản sao không được gọi?
Tôi đang sử dụng g ++ (Ubuntu/Linaro 4.6.1-9ubuntu3) 4.6.1
Điều này thực sự lạ ... Nó thậm chí có thể tái sản xuất tại ideone ... – RedX
Sooo cool. :) Tôi cũng sao chép điều đó, mặc dù tôi không tin điều đó. –
có thể trình biên dịch đơn giản di chuyển b đến a vì b không được sử dụng sau khi gán? Bạn đã thử làm gì đó với b sau a = b (in ấn, vv)? – user396672