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.
这篇关于返回值的复制构造函数何时发生的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:返回值的复制构造函数何时发生
				
        
 
            
        基础教程推荐
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
 - 如何通过C程序打开命令提示符Cmd 2022-12-09
 - 我有静态或动态 boost 库吗? 2021-01-01
 - 如何在 C++ 中初始化静态常量成员? 2022-01-01
 - 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
 - C++结构和函数声明。为什么它不能编译? 2022-11-07
 - 如何检查GTK+3.0中的小部件类型? 2022-11-30
 - 在 C++ 中计算滚动/移动平均值 2021-01-01
 - 这个宏可以转换成函数吗? 2022-01-01
 - 常量变量在标题中不起作用 2021-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				