Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does the C++ default assignment operator become unaccessible?

Tags:

c++

If I define an own assignment operator, which has a different signature than the normally generated default assignment operator:

struct B;
struct A {
void operator = (const B& b) {
    // assign something
}
};

does the default assignment operator, in this case operator = (A&) (or the like, correct me if wrong) become undefined/unaccessible?

AFAIK this is true for the default constructor, which doesn't exist, if we define some other constructor. But I am really not sure if this is the case for the other "magic" defaults.

The reason I ask: I want to avoid that the default copy constructor is accidently called via a implicit type conversion. If it doesn't exist, it could never happen.

like image 812
Gunther Piez Avatar asked Aug 19 '09 12:08

Gunther Piez


People also ask

What is the default assignment operator?

If a class definition does not declare a parameterless constructor, a copy constructor, a copy assignment operator, or a destructor, the compiler will implicitly declare them. These are called default operators.

Is assignment operator overloaded by default?

Which of the following operators are overloaded by default by the compiler in every user defined classes even if user has not written? Explanation: Assign operator is by default available in all user defined classes even if user has not implemented. The default assignement does shallow copy.

What happens if you don't define a copy assignment operator?

If no user-defined copy assignment operators are provided for a class type (struct, class, or union), the compiler will always declare one as an inline public member of the class.

Is assignment operator overloaded by default in C++?

Assignment Operators Overloading in C++You can overload the assignment operator (=) just as you can other operators and it can be used to create an object just like the copy constructor. Following example explains how an assignment operator can be overloaded.


2 Answers

No. 12.8/9 says that the assignment operator for class X must be non-static, non-template with a parameter of type X, X&, X const&, X volatile& or X const volatile&. And there is a note which emphasizes that the instantiation of a template doesn't suppress the implicit declaration.

like image 102
AProgrammer Avatar answered Oct 20 '22 15:10

AProgrammer


Since A& operator=( B& ) has not the signature of A& operator=( const A& ), this does nothing to the synthesized assignement operator.

Take a look at this snippet at codepad.org - as far as an example counts as proof.

Test driving Comeau with it also shows that A& operator=( const A& ) is synthesized.

like image 4
xtofl Avatar answered Oct 20 '22 13:10

xtofl