使用 std::mutex 复制省略号

Copy elision with std::mutex

This explanation of copy elision 表示

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:

T f() { return T(); }
f(); // only one call to default constructor of T

我的问题是为什么下面的代码不能编译:

#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

因为您引用的参考资料说

(since C++17)

它不适用于旧的 C++ 标准。您使用 C++14 编译器编译了该程序。在 C++14 中,返回的对象是移动的,所以类型必须是可移动的,而 std::mutex 不是。移动可能作为优化被省略,但这种可能性不会消除可移动性要求。

该示例在 C++17 中格式正确,将使用兼容的编译器进行编译。