C ++中引用成员默认初始化程序的生命周期是多少?
What is the lifetime of reference member default initializer in C++?
请考虑这个简短的代码示例:
#include <iostream>
struct A
{
A() { std::cout << "A() "; }
~A() { std::cout << "~A() "; }
};
struct B { const A &a = A(); };
int main()
{
B x;
std::cout << ". ";
auto y = B();
std::cout << ". ";
auto z = B{};
std::cout << ". ";
}
GCC 在此处打印 (https://gcc.godbolt.org/z/a83bn54qT):
A() ~A() . A() ~A() . A() . ~A()
表示A
-对象初始化引用在x
和y
中的生命周期很短,但在z
中生命周期延长到结束范围。
能否从 C++ 标准的角度解释一下为什么会这样?
无法保证生命周期延长,因为代码格式错误。
A temporary expression bound to a reference member from a default
member initializer is ill-formed. [Example 8:
struct A {
A() = default; // OK
A(int v) : v(v) { } // OK
const int& v = 42; // OK
};
A a1; // error: ill-formed binding of temporary to reference
A a2(1); // OK, unfortunately
— end example]
请考虑这个简短的代码示例:
#include <iostream>
struct A
{
A() { std::cout << "A() "; }
~A() { std::cout << "~A() "; }
};
struct B { const A &a = A(); };
int main()
{
B x;
std::cout << ". ";
auto y = B();
std::cout << ". ";
auto z = B{};
std::cout << ". ";
}
GCC 在此处打印 (https://gcc.godbolt.org/z/a83bn54qT):
A() ~A() . A() ~A() . A() . ~A()
表示A
-对象初始化引用在x
和y
中的生命周期很短,但在z
中生命周期延长到结束范围。
能否从 C++ 标准的角度解释一下为什么会这样?
无法保证生命周期延长,因为代码格式错误。
A temporary expression bound to a reference member from a default member initializer is ill-formed. [Example 8:
struct A { A() = default; // OK A(int v) : v(v) { } // OK const int& v = 42; // OK }; A a1; // error: ill-formed binding of temporary to reference A a2(1); // OK, unfortunately
— end example]