在自动var销毁之前或之后创建的C ++返回值? [英] C++ return value created before or after auto var destruction?

查看:209
本文介绍了在自动var销毁之前或之后创建的C ++返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中是一个返回值,保证在函数中的自动变量被销毁之前创建? Notice Basket :: get:

In C++ is a return value guaranteed to be created before automatic variables in the function are destroyed? Notice Basket::get:

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来执行它的礼物拷贝构造函数销毁锁对象。否则,正在退回的礼物对象可能会被同时调用put损坏。

I need Basket::get to perform its Gift copy constructor (of the temp object returned) prior to destruction of the lock object. Otherwise the gift object being returned can be corrupted by a simultaneous call to put.

我的测试显示礼物副本确实是在锁销毁之前创建的,但是,如果没有,我需要在函数中创建第二个临时函数,例如:

My tests show the gift copy is indeed created before lock destruction, however, is it guaranteed? If not, I'll need to create a second temporary inside the function, such as:

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


推荐答案

保持在范围内,直到返回完成后。如果您使用优化 return 的编译器,尤其如此:

Yes, the auto variable will remain in scope until after the return is finished. This is especially true if you are using a compiler that optimizes the return, eg:

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

Gift g = basket.get();

这个顺序应该是等同的:

Which would be equivilent to this sequence:

Gift g;
Lock lock(mutex);
g = Gift(gift);
~lock();

可以进行优化以更类似这样:

May be optimized to act more like this:

void get(Gift &ret) 
{ 
    Lock lock(mutex);
    ret = gift;
} 

Gift g;
basket.get(g);

这个顺序应该是等同的:

Which would be equivilent to this sequence:

Gift g;
Lock lock(mutex);
g = gift;
~lock();

换句话说,在 return

这篇关于在自动var销毁之前或之后创建的C ++返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆