Disable copy constructor

Humble Debugger picture Humble Debugger · May 20, 2011 · Viewed 132.2k times · Source

I have a class :

class SymbolIndexer {
protected:
  SymbolIndexer ( ) { }

public:
  static inline SymbolIndexer & GetUniqueInstance ( ) 
  { 
    static SymbolIndexer uniqueinstance_ ;
    return uniqueinstance_ ; 
  }
};

How should I modify it to disable code like:

SymbolIndexer symbol_indexer_ = SymbolIndexer::GetUniqueInstance ( );

and only allow code like :

SymbolIndexer & ref_symbol_indexer_ = SymbolIndexer::GetUniqueInstance ( );

Answer

R. Martinho Fernandes picture R. Martinho Fernandes · May 20, 2011

You can make the copy constructor private and provide no implementation:

private:
    SymbolIndexer(const SymbolIndexer&);

Or in C++11, explicitly forbid it:

SymbolIndexer(const SymbolIndexer&) = delete;