我有TestClass
一个const&
成员变量。我从不同的地方和自己的经验中知道,const&
使用临时值的引用来初始化它是一个坏主意。所以我很惊讶下面的代码可以很好地编译(用gcc-4.9.1
,clang-3.5
和测试scan-build-3.5
)但是不能正常运行。
class TestClass {
public:
// removing the "reference" would remove the temporary-problem
const std::string &d;
TestClass(const std::string &d)
: d(d) {
// "d" is a const-ref, cannot be changed at all... if it is assigned some
// temporary value it is mangled up...
}
};
int main() {
// NOTE: the variable "d" is a
// temporary, whose reference is not valid... what I don't get in the
// moment: why does no compiler warn me?
TestClass dut("d");
// and printing what we got:
std::cout << "beginning output:\n\n";
// this will silently abort the program (gcc-4.9.1) or be empty
// (clang-3.5) -- don't know whats going on here...
std::cout << "dut.d: '" << dut.d << "'\n";
std::cout << "\nthats it!\n";
return 0;
}
为什么两个编译器都没有在编译时警告我?另请参阅此ideone,正在进行更多测试。