我有一个名为
为什么这两个编译器在编译时都没有警告我呢?另请参考ideone,其中有更多的测试。
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,其中有更多的测试。
"d"
不是一个变量,它是一个字符串字面值。然而,将其传递给期望std::string
的函数会创建一个临时的std::string
对象。 - Some programmer dude