const class 可以延长 temporary 的 const 成员 ref 的生命周期?
const class can extend lifetime of const member ref of temporary?
struct A {
// something
~A() { std::cout << "A destruct!\n"; }
};
class refWrapper {
public:
refWrapper(const A& a) : a_(a) {}
~refWrapper() { std::cout << "refWrapper destruct!\n"; }
private:
const A& a_;
};
void func(const refWrapper& ref = A()) {
// why ~A after ~refWrapper
// Rather than after refWrapper constructor complete
}
使用默认参数,调用
func();
等同于
func(A()); // so func(refWrapper(A()));
所以,
- 首先创建临时的
A
(在完整表达式结束时销毁)
- 第二个创建临时
refWrapper
(绑定到参数引用)
- 临时
refWrapper
销毁。
- 临时
A
销毁。
注意有一个 exception for lifetime extension or parameter:
A temporary object bound to a reference parameter in a function call ([expr.call]) persists until the completion of the full-expression containing the call.
所以 refWrapper
在完整表达式结束时被销毁,而不是在 func
调用结束时(尽管在给定示例中是同一时刻)。所以破坏应该按照构造的相反顺序进行。
struct A {
// something
~A() { std::cout << "A destruct!\n"; }
};
class refWrapper {
public:
refWrapper(const A& a) : a_(a) {}
~refWrapper() { std::cout << "refWrapper destruct!\n"; }
private:
const A& a_;
};
void func(const refWrapper& ref = A()) {
// why ~A after ~refWrapper
// Rather than after refWrapper constructor complete
}
使用默认参数,调用
func();
等同于
func(A()); // so func(refWrapper(A()));
所以,
- 首先创建临时的
A
(在完整表达式结束时销毁) - 第二个创建临时
refWrapper
(绑定到参数引用) - 临时
refWrapper
销毁。 - 临时
A
销毁。
注意有一个 exception for lifetime extension or parameter:
A temporary object bound to a reference parameter in a function call ([expr.call]) persists until the completion of the full-expression containing the call.
所以 refWrapper
在完整表达式结束时被销毁,而不是在 func
调用结束时(尽管在给定示例中是同一时刻)。所以破坏应该按照构造的相反顺序进行。