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.
这篇关于返回值的复制构造函数何时发生的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:返回值的复制构造函数何时发生
基础教程推荐
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- CString 到 char* 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
