gpt4 book ai didi

c++ - 本地对象是否保证比临时参数长寿? (C++11)

转载 作者:搜寻专家 更新时间:2023-10-30 23:53:47 24 4
gpt4 key购买 nike

如果我有一个设置,其中函数将对象 Bar 作为参数,将该对象传递给本地类 FooFoo 在其析构函数中使用 Bar,例如:

class Foo {
public:
Foo(const Bar& bar) : bar_(bar) {}
~Foo() {
bar_.DoSomething();
}
private:
const Bar& bar_;
};

void example_fn(const Bar& input_bar) {
Foo local_foo(input_bar);
// ... do stuff.
// When foo goes out of scope, its destructor is called, using input_bar.
}

如果 example_fn 使用临时 Bar input_bar 调用,局部变量 Foo local_foo 是否保证在临时参数之前被销毁?换句话说,参数是否保证比局部变量长?

最佳答案

is the local variable Foo local_foo guaranteed to be destroyed before the temporary argument?

是的,具有自动存储持续时间的对象(又名本地对象)保证以相反的构造顺序销毁。函数参数总是在 block 范围内的局部变量之前构造(以未指定的顺序)。参见 Object Destruction in C++

[class.temporary/5]

5: ...In addition, the destruction of temporaries bound to references shall take into account the ordering of destruction of objects with static, thread, or automatic storage duration ([basic.stc.static], [basic.stc.thread], [basic.stc.auto]); that is, if obj1 is an object with the same storage duration as the temporary and created before the temporary is created the temporary shall be destroyed before obj1 is destroyed; if obj2 is an object with the same storage duration as the temporary and created after the temporary is created the temporary shall be destroyed after obj2 is destroyed. ...

关于c++ - 本地对象是否保证比临时参数长寿? (C++11),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38334726/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com