我有这个示例代码:
struct A
{
bool test() const
{
return false;
}
};
template <typename T = A>
class Test
{
public:
Test(const T& t = T()) : t_(t){}
void f()
{
if(t_.test())
{
//Do something
}
}
private:
const T& t_;
};
int main()
{
Test<> a;
a.f();
}
基本上我担心Test
的构造函数,我将const引用存储到临时变量并在methof f
中使用它。临时对象引用在f
内是否仍然有效?
答案 0 :(得分:7)
它不会保持有效。初始化a
后,临时对象将被销毁。在您调用f
时,您可以通过调用test
来调用未定义的行为。只有以下内容有效:
// Valid - both temporary objects are alive until after the
// full expression has been evaluated.
Test<>().f();