返回值的复制构造函数何时发生

When is the copy constructor for the return value happens(返回值的复制构造函数何时发生)

本文介绍了返回值的复制构造函数何时发生的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下成员函数:

Person ClassB::DoSomethingAndReturnPerson()
{
 RAIIMutex myLock(&m_mutex);
 return m_person;
}

RAIIMutex 是一个辅助类,它接收互斥体并将其锁定在构造函数中并在析构函数中释放.

RAIIMutex is an helper class that recieves a mutex and locks it in the constructor and releases in the destructor.

m_person 属于 Person 类型(尺寸非常小).其他线程中的其他函数可能会更改此成员.

m_person is of type Person (something very small in size). Other functions in other threads might change this member.

我想按值返回 m_person(返回一个副本),当然我想避免 m_person 在被复制时在另一个线程中被更改的情况在返回中,所以我添加了锁.

I want to return m_person by value (return a copy) and of course I want to avoid the situation where the m_person being changed in another thread while it's being copied in the return so I've added the lock.

但是首先会发生什么呢?编译器是先创建 m_person 的副本还是先调用 myLock 的析构函数?

But what happens first ? Does the compiler first creates a copy of m_person or first calls the destructor of myLock ?

理论上,这样做很容易解决:

Theoretically it easly solvable by doing something like this :

Person ClassB::DoSomethingAndReturnPerson()
{
 RAIIMutex myLock(&m_mutex);
 Person tmp = m_person;
 return tmp;
}

但我很想知道我的问题的答案.

But I'm interested in knowing the answer to my question.

谢谢

推荐答案

之前会处理返回值的拷贝初始化.

The copy-initialization of the returned value will be processed before.

从标准来看,[stmt.return]/3 (强调我的)

From the standard, [stmt.return]/3 (emphasis mine)

调用结果的复制初始化顺序在之前完整表达结束时的临时性破坏由 return 语句的操作数建立,反过来,是在破坏局部变量([stmt.jump])之前排序包含 return 语句的块.

The copy-initialization of the result of the call is sequenced before the destruction of temporaries at the end of the full-expression established by the operand of the return statement, which, in turn, is sequenced before the destruction of local variables ([stmt.jump]) of the block enclosing the return statement.

这篇关于返回值的复制构造函数何时发生的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:返回值的复制构造函数何时发生

基础教程推荐