gpt4 book ai didi

c++ - 在自动var销毁之前或之后创建的C++返回值?

转载 作者:行者123 更新时间:2023-12-02 10:30:56 24 4
gpt4 key购买 nike

在C++中,是否保证可以在销毁函数中的自动变量之前创建返回值?公告栏::获取:

class Basket
{
public:
// Gift is a struct containing safely copyable things like int or string
Gift gift;
// Used to protect access and changes to gift
Mutex mutex;

// Copy gift into present, while locked to be thread safe
void put (const Gift & gift)
{
Lock lock(mutex); // Constructor locks, destructor unlocks mutex
this->gift = gift; // Gift assignment operator
}

// Return a memberwise-copy of gift, tries to be thread safe (but is it?)
Gift get ()
{
Lock lock(mutex); // Constructor locks, destructor unlocks mutex
return gift; // Gift copy constructor
}
};

我需要Basket::get来执行其Gift副本构造函数(返回的临时对象的礼物),然后销毁锁定对象。否则,同时调用put可能会损坏返回的礼物对象。

我的测试表明,礼物副本确实是在销毁锁之前创建的,但是可以保证吗?如果没有,我将需要在函数内部创建第二个临时文件,例如:
  Gift get ()
{
Gift result;
{
Lock lock(mutex);
result = gift;
}
return result;
}

最佳答案

是的,自动变量将保留在范围内,直到返回完成。如果您使用的是优化return的编译器,则尤其如此,例如:

Gift get() 
{
Lock lock(mutex);
return gift;
}

Gift g = basket.get();

等同于以下顺序:
Gift g;
Lock lock(mutex);
g = Gift(gift);
lock.~Lock();

可以进行优化以使其更像这样:
void get(Gift &ret) 
{
Lock lock(mutex);
ret = gift;
}

Gift g;
basket.get(g);

等同于以下顺序:
Gift g;
Lock lock(mutex);
g = gift;
lock.~Lock();

换句话说,可以在 return期间删除临时文件。

关于c++ - 在自动var销毁之前或之后创建的C++返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62307010/

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