Why delete of templete copy constructor cause assignment operator disfunctional? - c++

I have code like below which looks a little bit Confusing. I define a template class. It has a user-defined constructor. When I declare two objects of this template class by "operator =", its user-defined contructor is called to my surprise. Besides, After deleting its copy constructor, the compiling cannot even pass during resolution of "operator =". Does templete constructors have different rules than non-templete class?
#include "iostream"
using namespace std;
template <typename T>
class MyPtr
{
private:
T p_;
public:
MyPtr(T P = NULL): p_(P)
{
cout<<"track!!"<<endl;
}
//MyPtr(const MyPtr<T> & P) = delete;
~MyPtr()
{
}
};
int main()
{
int i=3;
int j=4;
MyPtr<int> p = i;
MyPtr<int> pp = j;
}

Does templete constructors have different rules than non-templete class?
No.
MyPtr<int> p = i; (and MyPtr<int> pp = j;) is copy initialization. Note that this is initialization but not assignment, as the effect p is initialized by the constructor MyPtr::MyPtr(T). e.g.
MyPtr<int> p = i; // initialization; constructors get called
p = j; // assignment; assignment operators (operator=) get called
Before C++17, i would be converted to MyPtr<int> via MyPtr::MyPtr(T) firstly, then the conversion result, i.e. the temporary MyPtr<int> is copied/moved to initialize p; even the copy/move operation is allowd to be optimized, the copy/move constructor is required to be accessible. Declaring copy constructor as delete makes copy constructor unusable and move constructor won't be generated, thus makes MyPtr<int> p = i; ill-formed until C++17.
Since C++17 the optimization is mandatory and the copy/move constructor is not required to be accessible again, that means your code would compile fine with C++17 mode even declaring copy constructor as delete.
If T is a class type, and the cv-unqualified version of the type of other is not T or derived from T, or if T is non-class type, but the type of other is a class type, user-defined conversion sequences that can convert from the type of other to T (or to a type derived from T if T is a class type and a conversion function is available) are examined and the best one is selected through overload resolution. The result of the conversion, which is a prvalue temporary (until C++17) prvalue expression (since C++17) if a converting constructor was used, is then used to direct-initialize the object. The last step is usually optimized out and the result of the conversion is constructed directly in the memory allocated for the target object, but the appropriate constructor (move or copy) is required to be accessible even though it's not used. (until C++17)

Related

Why is it illegal to bind an r-value to a const l-value reference in special member functions?

For function parameters, it is possible to bind an r-value to an l-value const reference.
However, this does not seem to apply to special member function like the copy-constructor, and copy-assignment operator in C++11 and C++14. Is there a motivation for this?
When using C++17, it is possible to copy-construct, but not copy assign, from an r-value.
Is there a motivation why only the behavior for the copy-constructor was changed here?
All of this is demonstrated in the following example:
struct B {
B() = default;
B(B const&) = default;
B(B&&) = delete;
B& operator=(B const&) = default;
B& operator=(B&&) = delete;
};
void bar(B const &) {}
int main() {
bar(B{}); // does work
B(B{}); // only works in C++17
B b{};
b = B{}; // doesn't work
}
B(B{}); works since C++17 because of mandatory copy elision, the move-construction is omitted completely; the temporary object is initialized by the default constructor directly.
(emphasis mine)
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:
...
In the initialization of an object, when the initializer expression is a prvalue of the same class type (ignoring cv-qualification) as the
variable type:
T x = T(T(f())); // only one call to default constructor of T, to initialize x
Note: the rule above does not specify an optimization: C++17 core language specification of prvalues and temporaries is fundamentally different from that of the earlier C++ revisions: there is no longer a temporary to copy/move from. Another way to describe C++17 mechanics is "unmaterialized value passing": prvalues are returned and used without ever materializing a temporary.
Before C++17 this is an optimization and B(B{}); is ill-formed.
This is an optimization: even when it takes place and the copy/move (since C++11) constructor is not called, it still must be present and accessible (as if no optimization happened at all), otherwise the program is ill-formed
bar(B{}); works because there's only one overlaod of bar which taking lvalue-reference to const, to which rvalues could be bound; this doesn't change since C++11.
b = B{}; doesn't work because the overloaded move assignment operator is selected; even it's marked as delete explicitly it still participates in overload resolution[1]. For bar if you add an overloading taking rvalue-reference as
void bar(B&&)=delete;
It'll be selected and cause the program ill-formed too.
[1] Note that it's not true for deleted implicitly declared move constructors, which are ignored by overload resolution. (since C++14)
The deleted implicitly-declared move constructor is ignored by overload resolution (otherwise it would prevent copy-initialization from rvalue).

How to avoid triggering this kind of copy constructor in c++11?

I want to create an object in a function and use it outside.
I write the following code under the c++17 standard, it seems ok.
#include <iostream>
struct Vector2 {
Vector2() = default;
Vector2(int x, int y) : x(x), y(y) {}
Vector2(const Vector2 &) = delete;
Vector2 &operator=(const Vector2 &) = delete;
int x = 0;
int y = 0;
};
Vector2 newVec(int x, int y) {
return Vector2(x, y);
}
int main() {
auto v = newVec(1, 2);
std::cout << v.x * v.y << std::endl;
return 0;
}
But when I switched to c++11 standard, I couldn't compile it.
note: 'Vector2' has been explicitly marked deleted here
Vector2(const Vector2 &) = delete;
I think I constructed a temporary Vector2 object in the newVec function. When return, Vector2 call copy constructor with the temporary variable as the argument. But I have marked copy constructor 'delete', so it can't be compiled.
My question is what is the equivalent code under the C++11 standard?
What did c++17 do to avoid this copy constructor?
What did c++17 do to avoid this copy constructor?
This:
auto v = newVec(1, 2);
was one of the motivating cases for a language feature called "guaranteed copy elision." The example from that paper:
auto x = make(); // error, can't perform the move you didn't want,
// even though compiler would not actually call it
Before C++17, that expression always copy-initialization. We deduce the type with auto, that gives us Vector2, and then we're trying to construct a Vector2 from an rvalue of type Vector2. That's the usual process - enumerating constructors, etc. The best match is your copy constructor, which is deleted, hence the whole thing is ill-formed.
Sad face.
In C++17, this is totally different. Initializing from a prvalue of the same type doesn't try to find a constructor at all. There is no copy or move. It just gives you a Vector2 that is the value of newVec(1, 2), directly. That's the change here - it's not that in C++17 that copy-initialization works, it's more that it's not even the same kind of initialization anymore.
My question is what is the equivalent code under the C++11 standard?
There is no way at all to construct a non-movable object like this. From the same paper:
struct NonMoveable { /* ... */ };
NonMoveable make() { /* how to make this work without a copy? */ }
If you want a function like make() (newVec() in your example) to work, the type has to be, at least, movable. That means either:
adding a move constructor
undeleting your copy constructor
if none of the above is possible, put it on the heap - wrap it in something like unique_ptr<Vector2>, which is movable
Or you pass into make() your object and have the function populate it internally:
void make(NonMoveable&);
This ends up being less compose-able, but it works. As written, it requires your type to be default constructible but there are ways around that as well.
You are observing guaranteed copy elision in C++17.
On the other hand, C++11 requires that a copy or move constructor is present and accessible even if the compiler ultimately decides to elide its invocation.
You need to either remove the explicit deletion of the copy constructor so that the move constructor gets generated(but so will be the copy constructor) or declare a move constructor like so:
Vector2(Vector2 &&) = default;
According to the standard,
If the definition of a class X does not explicitly declare a move
constructor, one will be implicitly declared as defaulted if and only
if
— X does not have a user-declared copy constructor,
— X does not have a user-declared copy assignment operator,
— X does not have a user-declared move assignment operator, and
— X does not have a user-declared destructor.
User-declared means either either user-provided (defined by the user), explicitly defaulted (= default) or explicitly deleted (= delete)
On the other hand in C++17, call to a copy/move constructor is omitted due to the reason described here:
Under the following circumstances, the compilers are permitted, but not required to omit the copy and move (since C++11) construction of class objects even if the copy/move (since C++11) constructor and the destructor have observable side-effects. The objects are constructed directly into the storage where they would otherwise be copied/moved to.
...
(Since C++17) In the initialization of an object, when the source object is a nameless temporary and is of the same class type (ignoring cv-qualification) as the target object. When the nameless temporary is the operand of a return statement, this variant of copy elision is known as RVO, "return value optimization".
(until C++17)
Return value optimization is mandatory and no longer considered as copy elision; see above.
You can fix it with two small changes:
return {x, y}; from newVec(). This will construct the object just once and not require a copy constructor.
const auto& v instead of auto v. This will have the same lifetime (but you can't modify it), and doesn't require a copy constructor.

Why is this direct initialization valid? (C++ 17)

Consider the following two classes:
class B
{
public:
B() { }
B(const B& b) = delete; //Move ctor not implicitly declared
};
class A
{
public:
A() { }
operator B()
{
return B();
}
};
I can see why this code compiles fine:
A a;
B b = a;
Following the rules of copy-initialization, the object "a" gets converted to a prvalue of type B and since in C++17 the copy constructor is not needed anymore there's no error:
If T is a class type, and the cv-unqualified version of the type of
other is not T or derived from T, or if T is non-class type, but the
type of other is a class type, user-defined conversion sequences that
can convert from the type of other to T (or to a type derived from T
if T is a class type and a conversion function is available) are
examined and the best one is selected through overload resolution. The
result of the conversion, which is a prvalue temporary (until
C++17)prvalue expression (since C++17) if a converting constructor was
used, is then used to direct-initialize the object. The last step is
usually optimized out and the result of the conversion is constructed
directly in the memory allocated for the target object, but the
appropriate constructor (move or copy) is required to be accessible
even though it's not used. (until C++17)
However why does this direct list-initialization compile too?
A a;
B b{ a };
I couldn't find any wording in the list-initialization stating the compiler should attempt to convert A into B in this case. Only that overload resolution on constructors is considered:
If the previous stage does not produce a match, all constructors of T
participate in overload resolution against the set of arguments that
consists of the elements of the braced-init-list, with the restriction
that only non-narrowing conversions are allowed
However in this case the copy constructor is deleted, so shouldn't it not be selected by overload resolution?
This is CWG 2327. You're correct as far as the standard goes, but some compilers additionally consider conversion functions in this context as well - because it really makes sense to.

Move constructor is required even if it is not used. Why?

Why?! Why C++ requires the class to be movable even if it's not used!
For example:
#include <iostream>
using namespace std;
struct A {
const int idx;
// It could not be compileld if I comment out the next line and uncomment
// the line after the next but the moving constructor is NOT called anyway!
A(A&& a) : idx(a.idx) { cout<<"Moving constructor with idx="<<idx<<endl; }
// A(A&& a) = delete;
A(const int i) : idx(i) { cout<<"Constructor with idx="<<i<<endl; }
~A() { cout<<"Destructor with idx="<<idx<<endl; }
};
int main()
{
A a[2] = { 0, 1 };
return 0;
}
The output is (the move constructor is not called!):
Constructor with idx=0
Constructor with idx=1
Destructor with idx=1
Destructor with idx=0
The code can not be compiled if moving constructor is deleted ('use of deleted function ‘A::A(A&&)’'. But if the constructor is not deleted it is not used!
What a stupid restriction?
Note:
Why do I need it for? The practical meaning appears when I am trying to initialize an array of objects contains unique_ptr field.
For example:
// The array of this class can not be initialized!
class B {
unique_ptr<int> ref;
public:
B(int* ptr) : ref(ptr)
{ }
}
// The next class can not be even compiled!
class C {
B arrayOfB[2] = { NULL, NULL };
}
And it gets even worse if you are trying to use a vector of unique_ptr's.
Okay. Thanks a lot to everybody. There is big confusion with all those copying/moving constructors and array initialization. Actually the question was about the situation when the compiler requires a copying consrtuctor, may use a moving construcor and uses none of them.
So I'm going to create a new question a little bit later when I get a normal keyboard. I'll provide the link here.
P.S. I've created more specific and clear question - welcome to discuss it!
A a[2] = { 0, 1 };
Conceptually, this creates two temporary A objects, A(0) and A(1), and moves or copies them to initialise the array a; so a move or copy constructor is required.
As an optimisation, the move or copy is allowed to be elided, which is why your program doesn't appear to use the move constructor. But there must still be a suitable constructor, even if its use is elided.
A a[2] = { 0, 1 };
This is aggregate initialization. §8.5.1 [dcl.init.aggr]/p2 of the standard provides that
When an aggregate is initialized by an initializer list, as specified in 8.5.4, the elements of the initializer list are taken as initializers for the members of the aggregate, in increasing subscript or member order. Each member is copy-initialized from the corresponding initializer-clause.
§8.5 [dcl.init]/p16, in turn, describes the semantics of copy initialization of class type objects:
[...]
If the destination type is a (possibly cv-qualified) class type:
If the initialization is direct-initialization, or if it is copy-initialization where the cv-unqualified version of the source
type is the same class as, or a derived class of, the class of the
destination, constructors are considered. The applicable constructors
are enumerated (13.3.1.3), and the best one is chosen through overload
resolution (13.3). The constructor so selected is called to initialize
the object, with the initializer expression or expression-list as its
argument(s). If no constructor applies, or the overload resolution is
ambiguous, the initialization is ill-formed.
Otherwise (i.e., for the remaining copy-initialization cases), user-defined conversion sequences that can convert from the source
type to the destination type or (when a conversion function is used)
to a derived class thereof are enumerated as described in 13.3.1.4,
and the best one is chosen through overload resolution (13.3). If the
conversion cannot be done or is ambiguous, the initialization is
ill-formed. The function selected is called with the initializer
expression as its argument; if the function is a constructor, the call
initializes a temporary of the cv-unqualified version of the
destination type. The temporary is a prvalue. The result of the call
(which is the temporary for the constructor case) is then used to
direct-initialize, according to the rules above, the object that is
the destination of the copy-initialization. In certain cases, an
implementation is permitted to eliminate the copying inherent in this
direct-initialization by constructing the intermediate result directly
into the object being initialized; see 12.2, 12.8.
Since 0 and 1 are ints, not As, the copy initialization here falls under the second clause. The compiler find a user-defined conversion from int to A in your A::A(int) constructor, calls it to construct a temporary of type A, then performs direct initialization using that temporary. This, in turn, means the compiler is required to perform overload resolution for a constructor taking a temporary of type A, which selects your deleted move constructor, which renders the program ill-formed.

Compiler optimization of implicit constructor conversion

In the following code, I expect A's constructor is called, followed by A's copy constructor. However, It turns out only constructor is get called.
// MSVC++ 2008
class A
{
public:
A(int i):m_i(i)
{
cout << "constructor\n";
}
A(const A& a)
{
m_i = a.m_i;
cout << "copy constructor\n";
}
private:
int m_i;
};
int main()
{
// only A::A() is called
A a = 1;
return 0;
}
I guess the compiler is smart enough to optimize away the second call, to initialize the object a directly with the constructor. So is it a standard-defined behavior or just implementation-defined?
It's standard, but there's no optimization involved.
Actually, I believe there is an optimization involved, but it's still entirely standard.†
This code:
A a = 1;
invokes the converting constructor†† of A. A has a single converting constructor A(int i) that allows an implicit conversion from int to A.
If you prepend the constructor declaration with explicit, you'll find the code won't compile.
class A
{
public:
explicit A(int i) : m_i(i) // Note "explicit"
{
cout << "constructor\n";
}
A(const A& a)
{
m_i = a.m_i;
cout << "copy constructor\n";
}
private:
int m_i;
};
void TakeA(A a)
{
}
int main()
{
A a = 1; // Doesn't compile
A a(1); // Does compile
TakeA(1); // Doesn't compile
TakeA(A(1)); // Does compile
return 0;
}
† After looking at the standard again, I may have been initially wrong.
8.5 Initializers [dcl.init]
12. The initialization that occurs in argument passing, function
return, throwing an exception (15.1), handling an exception (15.3),
and brace-enclosed initializer lists (8.5.1) is called
copy-initialization and is equivalent to the form
T x = a;
14. The semantics of initializers are as follows. The destination
type is the type of the object or reference being initialized and the
source type is the type of the initializer expression. The source type
is not defined when the initializer is brace-enclosed or when it is a
parenthesized list of expressions.
...
If the destination type is a (possibly cv-qualified) class type:
If the class is an aggregate (8.5.1), and the initializer is a brace-enclosed list, see 8.5.1.
If the initialization is direct-initialization, or if it is copy-initialization where the cv-unqualified version of the source type is the same class as, or a derived class of, the class of the destination, constructors are considered. The applicable constructors are enumerated (13.3.1.3), and the best one is chosen through overload resolution (13.3). The constructor so selected is called to initialize the object, with the initializer expression(s) as its argument(s). If no constructor applies, or the overload resolution is ambiguous, the initialization is ill-formed.
Otherwise (i.e., for the remaining copy-initialization cases), user-defined conversion sequences that can convert from the source type to the destination type or (when a conversion function is used) to a derived class thereof are enumerated as described in 13.3.1.4, and the best one is chosen through overload resolution (13.3). If the conversion cannot be done or is ambiguous, the initialization is ill-formed. The function selected is called with the initializer expression as its argument; if the function is a constructor, the call initializes a temporary of the destination type. The result of the call (which is the temporary for the constructor case) is then used to direct-initialize, according to the rules above, the object that is the destination of the copy-initialization. In certain cases, an implementation is permitted to eliminate the copying inherent in this direct-initialization by constructing the intermediate result directly into the object being initialized; see 12.2, 12.8.
...
So in one sense it is very much an optimization. But I wouldn't worry about it since it is explicitly allowed by the standard and just about every compiler nowadays does the elison.
For a much more thorough treatment on initialization, see this GotW article (#36). The article seems to agree with the above interpretation of the standard:
NOTE: In the last case ("T t3 = u;") the compiler could call both the
user-defined conversion (to create a temporary object) and the T copy
constructor (to construct t3 from the temporary), or it could choose
to elide the temporary and construct t3 directly from u (which would
end up being equivalent to "T t3(u);"). Since July 1997 and in the
final draft standard, the compiler's latitude to elide temporary
objects has been restricted, but it is still allowed for this
optimization and for the return value optimization.
†† ISO/IEC 14882:2003 C++ Standard reference
12.3.1 Conversion by constructor [class.conv.ctor]
1. A constructor declared without the function-specifier explicit
that can be called with a single parameter specifies a conversion from
the type of its first parameter to the type of its class. Such a
constructor is called a converting constructor. [Example:
class X {
// ...
public:
X(int);
X(const char*, int =0);
};
void f(X arg)
{
X a = 1; // a = X(1)
X b = "Jessie"; // b = X("Jessie",0)
a = 2; // a = X(2)
f(3); // f(X(3))
}
—end example]
2. An explicit constructor constructs objects just like non-explicit
constructors, but does so only where the direct-initialization syntax
(8.5) or where casts (5.2.9, 5.4) are explicitly used. A default
constructor may be an explicit constructor; such a constructor will be
used to perform default-initialization or valueinitialization (8.5).
[Example:
class Z {
public:
explicit Z();
explicit Z(int);
// ...
};
Z a; // OK: default-initialization performed
Z a1 = 1; // error: no implicit conversion
Z a3 = Z(1); // OK: direct initialization syntax used
Z a2(1); // OK: direct initialization syntax used
Z* p = new Z(1); // OK: direct initialization syntax used
Z a4 = (Z)1; // OK: explicit cast used
Z a5 = static_cast<Z>(1); // OK: explicit cast used
—end example]
No optimization here. When = is used in the initialization, it is eqivalent(nearly) to calling the constructor with the right hand side as an argument. So this:
A a = 1;
Is (mostly) equivalent to this:
A a(1);