question

flaviu avatar image
0 Votes"
flaviu asked RLWA32-6355 commented

Rule of 4 or 6 ?

If I create a class, without any method:

 class C
 {
 };

What default methods will create the compiler ? I am asking that, because I cannot verify it on my own.

As far as I know, the compiler create constructor, destructor, copy constructor, copy assignment. The question is, will create a move constructor and a move assignment (of course, they are acting like copy, not as move), but would they be created by default ?

c++
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

RLWA32-6355 avatar image
0 Votes"
RLWA32-6355 answered flaviu commented

Take a look at special-member-functions


· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Thank you, I have found here something similar: https://en.cppreference.com/w/cpp/language/rule_of_three

0 Votes 0 ·
IgorTandetnik-1300 avatar image
1 Vote"
IgorTandetnik-1300 answered RLWA32-6355 commented

Yes, both move constructor and move assignment operator are implicitly defined in this case. While it's difficult to directly observe the presence of a constructor, it's easy to observe the presence of an overloaded operator - it's a member function like any other and may have its address taken.

 #include <memory>
    
 class C {
 public:
     // Uncomment to observe an error due to missing copy constructor.
     // std::unique_ptr<int> p;
    
     // Uncomment to observe an error due to missing move constructor
     // C& operator=(const C&) {}
 };
    
 int main() {
     using CopyAssignment = C&(C::*)(const C&);
     using MoveAssignment = C&(C::*)(C&&);
    
     CopyAssignment copy_op = &C::operator=;
     MoveAssignment move_op = &C::operator=;
 }

Demo. If you uncomment std::unique_ptr member, the class will become move-only, and you'll see an error on the copy_op line, while move_op would still compile. If you uncomment the user-defined copy assignment, this will suppress the implicit move assignment, and you'll see an error on the move_op line.


· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

So, if there is any one of these functions is defined, the other ones are not available, and I need to declare it myself. Excellent answer, thank you !

0 Votes 0 ·

Microsoft's docs have summary here that you may find useful - explicitly-defaulted-and-deleted-functions


0 Votes 0 ·