This is my class
class A {
public:
A(int);
A(A const&) = delete;
A& operator=(const A& a) = delete;
// etc.
};
In another file I can call the constructor like this:
auto foo = A(123);
That resolves to the copy constructor and not the one I expect, why?
error C2280: 'mynamspace::A::A(const mynamespace::A &)': attempting to reference a deleted function
auto foo = A(123);
performs copy initialization, in concept,A(123)
constructs a temporaryA
byA::A(int)
firstly, thenfoo
is copy-initialized from the temporary by the copy constructor (PSA
doesn't have move constructor). Before C++17 the code is ill-formed because the copy constructor is marked asdelete
.Since C++17 the copy construction is elided completely because of mandatory copy elision and the code is well-formed.
and
(emphais mine)
Note that before C++17, copy elision is an optimization, even it might be performed the copy/move constructor still must be present and accessible.
You can upgrade your compiler to support C++17, or use direct initialization (to remove the requirement of usage of copy constructor).