tmatth
tmatth

Reputation: 499

privately or publicly inherit from boost::non_copyable?

Which practice would you recommend, and why?

class Foo : public boost::noncopyable {};

vs.

class Foo : private boost::noncopyable {};

I can't imagine needing to use an instance of Foo as a boost::noncopyable, so I'm leaning toward private inheritance in this case.

Upvotes: 22

Views: 2642

Answers (3)

Michael Ma
Michael Ma

Reputation: 922

According to the Boost document

It is intended to be used as a private base.

Upvotes: 3

Adam Badura
Adam Badura

Reputation: 5339

I think that from higher point of view it should be public inheritance. The reasons to make it private are purely technical.

Why? Because whether a type is copyable or not (and this is shown by inheriting from boost::noncopyable) is part of public interface. For example if the inheritance would be public you would be able to check (using "meta programming") whether type derives from boost::noncopyable and then reason about whether it is copyable or not.

Nikolai N Fetissov in his answer to this question points out that boost::noncopyable doesn't have virtual destructor and so should not be used as public base class. While that it a valid argument in general I think it is so unlikely that anyone ever would try to use (and delete in particular) an object by a pointer to boost::noncopyable that it makes the argument (in this particular case) purely academic.

Come on! If someone is so inclined to misuse code that he uses delete on a pointer to boost::noncopyable then there is no way to be safe. Sure you can make it a bit harder but a programmer so determined will find some other way to misuse code anyway.

Also it seems that in C++11 boost::noncopyable could solve that issue by declaring default protected destructor:

protected:
    ~noncopyable() = default;

This way there should be no additional cost of declaring destructor (since we made it default) while we are protected from delete on a pointer to boost::noncopyable.

On the other hand however it also seems unlikely that anyone will be willing to check whether a type is copyable by checking inheritance from boost::noncopyable. Mostly because it doesn't provide complete answer. Just because a type doesn't derive from boost::noncopyable it doesn't mean that it is copyable.

Note also that Boost.Noncopyable docs suggest use of private inheritance.

Upvotes: 3

Nikolai Fetissov
Nikolai Fetissov

Reputation: 84189

boost::noncopyable does not declare a virtual destructor, i.e. is not designed to be the base of public inheritance chain. Always inherit from it privately.

Upvotes: 26

Related Questions