Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does boost::noncopyable require inheritance

Adding any noncopyable member to a class would prevent the automatic generation of copy construction and assignment operator. Why does boost require inheritance to use noncopyable?

I think I am not alone in my stylistic preference for

class MyUtility : public MyBase {    noncopyable guard;    ... }; 

as opposed to

class MyUtility : public MyBase , private noncopyable {    ... }; 

Dave Abrahams is a smart guy, so he probably considered this possibility. What am I missing? What does inheritence accomplish?

like image 297
Mark Borgerding Avatar asked Jan 28 '11 15:01

Mark Borgerding


People also ask

What is boost :: NonCopyable?

Boost::noncopyable prevents the classes methods from accidentally using the private copy constructor. Less code with boost::noncopyable.

How do I make my class non copyable?

class NonCopyable { public: NonCopyable (const NonCopyable &) = delete; NonCopyable & operator = (const NonCopyable &) = delete; protected: NonCopyable () = default; ~NonCopyable () = default; /// Protected non-virtual destructor }; class CantCopy : private NonCopyable {};


2 Answers

Because sizeof(boost::noncopyable)!=0. So in this case your class size will be bigger.

Here you can read about the empty base optimization. (look at section "4.7: The Empty Member Optimization").

Edit: The fact, that noncopyable doesn't have public constructors makes it useless for any other use, while classes with public constructor could also be used for other wrong purposes. This is a another reason, why boost chose this approach.

like image 57
UmmaGumma Avatar answered Oct 02 '22 00:10

UmmaGumma


If you could use noncopyable as a member, it would require a public default constructor and destructor. Then people could create instances of noncopyable or even use it as a polymorphic base class without the destructor being virtual. The implementation without any public members simply ensures that it is used solely as a policy class.

like image 22
Philipp Avatar answered Oct 02 '22 02:10

Philipp