3

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.

2
  • mutex as return value? WAT? You are doing something terribly wrong. Commented Sep 5, 2019 at 12:39
  • @MarekR I don't think so. Commented Sep 5, 2019 at 13:51

1 Answer 1

11

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@StaceyGirl I still had the timeout at the time I wrote my comment. Ofc I will accpet a good answer!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.