rozina
rozina

Reputation: 4232

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:

T f() { return T(); }
f(); // only one call to default constructor of 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.

Upvotes: 3

Views: 178

Answers (1)

eerorika
eerorika

Reputation: 238421

My question is why does the following code not compile then

Because the reference that you quote says

(since C++17)

It does not apply to older C++ standards. You compiled the program with a C++14 compiler. In C++14, the returned object is moved, so the type must be movable, which std::mutex is not. 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.

Upvotes: 11

Related Questions