简体   繁体   English

使用std :: mutex复制elision

[英]Copy elision with std::mutex

This explanation of copy elision states that 对复制省略的这种解释说明了这一点

Under the following circumstances, the compilers are required to omit the copy and move construction of class objects, even if the copy/move constructor and the destructor have observable side-effects. 在下列情况下,编译器需要省略复制和移动类对象的构造,即使复制/移动构造函数和析构函数具有可观察到的副作用。 The objects are constructed directly into the storage where they would otherwise be copied/moved to. 对象直接构造到存储器中,否则它们将被复制/移动到存储器中。 The copy/move constructors need not be present or accessible, as the language rules ensure that no copy/move operation takes place, even conceptually: 复制/移动构造函数不需要存在或可访问,因为语言规则确保不会发生复制/移动操作,甚至在概念上:

In a return statement, when the operand is a prvalue of the same class type (ignoring cv-qualification) as the function return type: 在return语句中,当操作数是与函数返回类型相同的类类型(忽略cv-qualification)的prvalue时:

T f() { return T(); T f(){return T(); } }
f(); F(); // only one call to default constructor of T //只调用一次T的默认构造函数

My question is why does the following code not compile then: 我的问题是为什么下面的代码不能编译呢:

#include <mutex>

std::mutex createMutex()
{
    return std::mutex();
}

int main()
{
    auto mutex = createMutex();
}

Example program with compile errors. 带编译错误的示例程序。

My question is why does the following code not compile then 我的问题是为什么下面的代码不能编译呢

Because the reference that you quote says 因为你引用的引用说

(since C++17) (自C ++ 17起)

It does not apply to older C++ standards. 它不适用于较旧的C ++标准。 You compiled the program with a C++14 compiler. 您使用C ++ 14编译器编译了该程序。 In C++14, the returned object is moved, so the type must be movable, which std::mutex is not. 在C ++ 14中,返回的对象被移动,因此类型必须是可移动的,而std::mutex则不是。 The move may be elided as an optimisation, but that possibility does not remove the movability requirement. 此举可能被视为优化,但这种可能性并未消除可动性要求。

The example is well-formed in C++17 and will compile using a compliant compiler. 该示例在C ++ 17中构造良好,并将使用兼容的编译器进行编译。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM