简体   繁体   中英

Why would you =delete implicitly deleted default constructors and what is the point?

I am trying to delete all the copy/move ctor/assignment operators that are implicitly provided, but why am i still able to explicitly delete the default ctor that was supposed to be implicitly deleted?

I have tried =default-ing all the copy/move ctor/assignment operators implicitly provided only to then be told to actually =delete rather than =default. If my understanding of implicit/explicit is correct, the default ctor should be implicitly deleted if the user provides an explicit copy ctor.

I have the following class:

class A {
public:
   A() =delete;       
   A(const A&):...{;} --> my explicitly defined copy ctor
   ...
}

I expected the compiler to tell me that i cant =delete an implicitly deleted default ctor, but that is not the case. I am using clang8 to complile.

You simply can delete everything you want, fully independent if it was already (implicit) deleted or not.

It is a good idea to show that you did not want to have a default generated function like operators or constructors and "mark" them as deleted. This helps for clarification of the interface!

But: You still can instantiate your class even if you delete the constructor(s)!

class A { 
    public:
        A() =delete;
        A(int) = delete;

        int a;

        void Print() const { std::cout << a << std::endl; }
};  

int main()
{   
    A a{42};
    a.Print();
}  

See: https://en.cppreference.com/w/cpp/language/aggregate_initialization

From you comment:

I don't want the next programmer to have to look up the inheritance chain to try and figure out what is not already implicitly deleted.

As long as you define a single constructor and do not explicit enable using of base constructors with:

 using X::X;

nobody has the need of looking to the base class constructors at all. As said: It is a good idea to mark "unwanted" methods as delete but there are cases, where that did not help in any case as shown above!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM