首先是什么-堆栈展开或返回值的复制 [英] What comes first - stack unwinding or copying of return values

查看:77
本文介绍了首先是什么-堆栈展开或返回值的复制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

方法 GetValues()中使用的互斥锁是在之前之后副本中发布的,以构造 dummy 实例?

Is the mutex used in method GetValues() released before or after copy constructing the dummy instance?

class Protect
{};

class Test
{
public:
    Protect GetValues() const;

private:
    Protect m_protVal;
    Mutex m_mutex;
};

Protect Test::GetValues() const
{
    CLockGuard lock(m_mutex);

    return m_protVal;
}

int main(int argc, char** argv)
{
    Test myTestInstance;

    Protect dummy = myTestInstance.GetValues();
}

我们假设 CLockGuard Mutex 是boost库提供的标准类。

Let's assume CLockGuard and Mutex are standard classes provided with boost lib.

推荐答案

是: -)。正式而言,有两份副本当返回
值时:一个实际用于返回值的特殊位置,
返回值后的第二个位置,该值必须最终放置在
处。但是,可以优化其中一个或两个。局部变量的销毁
发生在第一个之后,但是在第二个之前。 (NRVO
和RVO可能会导致第一个被优化,但它们不会影响
您的代码,因为您没有返回本地变量。)

Yes:-). Formally, there are two “copies” when returning a value: one to some special place used to actually return the value, and the second after the return, to wherever the value must be finally placed. Either or both can be optimized out, however. The destruction of local variables occurs after the first, but before the second. (NRVO and RVO may lead to the first being optimized out, but they don't affect your code, since you're not returning a local variable.)

这篇关于首先是什么-堆栈展开或返回值的复制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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