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.
这篇关于返回值的复制构造函数何时发生的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:返回值的复制构造函数何时发生
基础教程推荐
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01