Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a std::noncopyable (or equivalent)?

There's a boost::noncopyable and I have my own noncopyable class in my library. Is there a std::noncopyable or equivalent knocking around in the latest C++ standard?

It's a small thing but deriving from such a class makes the intention much clearer.

like image 602
Robinson Avatar asked Aug 11 '15 11:08

Robinson


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 {};


1 Answers

No, because there is a standard way to make a class non-copyable:

class MyClass {    MyClass(const MyClass&) = delete;    MyClass& operator=(const MyClass&) = delete; }: 

A class that is non-copyable can however be made movable by overloading a constructor from MyClass&&.

The declaration to make the class non-copyable (above) can be in the public or private section.

If you don't really want to type all that out every time, you can always define a macro something like:

#define NONCOPYABLE(Type) Type(const Type&)=delete; Type& operator=(const Type&)=delete  class MyClass {     NONCOPYABLE(MyClass);      // etc. };       
like image 134
CashCow Avatar answered Sep 20 '22 18:09

CashCow