3

I'd like to make object of class not copyable so I put copy constructor and operator= in private section. However one class is friend of this class so it has access to private methods. Is it good idea to put throw exception in copy constructor and operator= to be sure that object will not be copied?

scdmb
  • 15,091
  • 21
  • 85
  • 128
  • Note that you should take the given advice always, not only if you have friends, because the class itself shouldn't be able to make copies of its kind either. – UncleBens Oct 14 '11 at 14:20

2 Answers2

6

One approach to make it not copyable is just to declare the copy constructor, but don't implement it at all. That will force a linker error at compile time if anyone tries to use it.

class foo
{
private:
    foo(const foo&); // not defined
    foo& operator=(const foo&); // not defined
};
GManNickG
  • 494,350
  • 52
  • 494
  • 543
Mysticial
  • 464,885
  • 45
  • 335
  • 332
3

@Mysticial have answered this question which is usually done in C++03. But in C++11, you can do this, more nicely:

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

The =delete conveys the message that foo doesn't support copy-semantic, as it has been disabled by explicitly marking it with delete. I've explained this in detail here:

Community
  • 1
  • 1
Nawaz
  • 353,942
  • 115
  • 666
  • 851