Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a C++ class produce non cloneable objects

How can I make a Class non-cloneable like we can do in Java while creating singleton.

Is there any condition we can put on copy constructor so that an exception can be thrown if user tries to make a copy of an object?

I am a novice in C++ so kindly add any info to this or redirect if an answer is already available for the same.

like image 705
Sanyam Goel Avatar asked Jan 21 '26 18:01

Sanyam Goel


1 Answers

Just declare copy constructor and copy assign operator private

in C++03

class NonCopyable
{
public:
   NonCopyable() { }

private:
   NonCopyable(const NonCopyable&);
   NonCopyable& operator=(const NonCopyable&);

};

Also you can make a class derive from NonCopyable, AnotherType is un-copyable

class AnotherNonCopyable : private NonCopyable
{
   public:
     AnotherNonCopyable () {}
}

With C++11:

class NonCopyableType
{
public:
  NonCopyableType(const NonCopyableType&) = delete;
  NonCopyableType& operator=(const NonCopyableType&) = delete;
};
like image 191
billz Avatar answered Jan 23 '26 09:01

billz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!