有一个持有引用的类,我希望下面的代码会失败,但它可以编译:
#include <iostream>
struct ReferenceHolder
{
std::string& str;
ReferenceHolder(std::string& str)
: str(str)
{}
};
// Why does this compile?
ReferenceHolder f() {
std::string str = "Hello";
return ReferenceHolder(str);
}
int main() {
ReferenceHolder h = f();
std::cout << "Should be garbage: " << h.str << '\n';
return 0;
}
编译器:g++ 4.7.2(带 -std=c++11)
编辑:即使使用 -fno-elide-constructors 它也能愉快地编译
最佳答案
复制初始化您的类没有问题,就像您的示例一样:新引用只是初始化为引用与旧引用相同的对象。当然,当函数返回使引用悬空时,您会得到未定义的行为。
引用防止默认初始化和复制分配;因此,由于这些原因,以下小更改将失败:
ReferenceHolder h; // ERROR: can't default-initialise the reference
h = f(); // ERROR: can't reassign the reference.
关于c++ - 为什么类持有可复制的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22893624/