鉴于Bar
未初始化状态实际上对赋值运算符很重要,我收到来自 GCC 的警告:
#include <iostream>
struct Bar {
int n;
Bar(int v) : n(v) {
std::cout << "Bar " << n << " constructed\n";
}
Bar& operator=(const Bar& other) {
std::cout << "Bar " << n << " assigned from " << other.n << "\n";
n = other.n;
return *this;
}
};
struct Foo
{
Bar a;
Bar b;
Foo(Bar c, Bar d) : a(b = c), b(d) { }
};
int main()
{
Foo f(Bar(1), Bar(2));
}
测试:https ://ideone.com/VDZzG
test.cc: In function ‘int main()’:
test.cc:8:32: warning: ‘*((void*)(& f)+4).Bar::n’ is used uninitialized in this function [-Wuninitialized]
test.cc:23:13: note: ‘*((void*)(& f)+4).Bar::n’ was declared here
不过,我尝试过的其他编译器似乎并不在意……