prohibit creation of object copies

  • Thread starter Wolfgang Jeltsch
  • Start date
W

Wolfgang Jeltsch

Hello,

what is the best way to prevent the user of a class from making copies of
objects of this class? Making the copy constructor private is a solution but I'm
looking for a better one.

Thanks,
Wolfgang
 
R

Ron Natalie

Wolfgang Jeltsch said:
Hello,

what is the best way to prevent the user of a class from making copies of
objects of this class? Making the copy constructor private is a solution but I'm
looking for a better one.

We make the copy constructor (and also frequently the assignment op) private
and we don't implement it. Not only does this give compile errors when you
try to make external copies, but (at least on our systems) link errors if you
try to make copies inside the class.
 
R

Rolf Magnus

Wolfgang said:
Hello,

what is the best way to prevent the user of a class from making copies
of objects of this class? Making the copy constructor private is a
solution but I'm looking for a better one.

Better in which regard? It's quite simple, does the job and is the usual
technique, so what could be done 'better'?
 
T

Thomas Matthews

Wolfgang said:
Hello,

what is the best way to prevent the user of a class from making copies
of objects of this class? Making the copy constructor private is a
solution but I'm looking for a better one.

Thanks,
Wolfgang

Search the web for "Singleton Design Pattern".
Also search this newsgroup and
--
Thomas Matthews

C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.raos.demon.uk/acllc-c++/faq.html
Other sites:
http://www.josuttis.com -- C++ STL Library book
 
F

Filipe Sousa

Wolfgang said:
Hello,

what is the best way to prevent the user of a class from making copies of
objects of this class? Making the copy constructor private is a solution
but I'm looking for a better one.

Thanks,
Wolfgang

I find this more elegant

class NonCopyable
{
protected:
NonCopyable() {}

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

class Derived : public NonCopyable {}
 
T

tom_usenet

I find this more elegant

class NonCopyable
{
protected:
NonCopyable() {}

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

class Derived : public NonCopyable {}

Or, similarly,

#include <boost/utility.hpp>

class Derived: boost::noncopyable {};

Tom
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top