我有一门课:
class SymbolIndexer {
protected:
SymbolIndexer ( ) { }
public:
static inline SymbolIndexer & GetUniqueInstance ( )
{
static SymbolIndexer uniqueinstance_ ;
return uniqueinstance_ ;
}
};
我应该如何修改它来禁用代码,如下所示:
SymbolIndexer symbol_indexer_ = SymbolIndexer::GetUniqueInstance ( );
并且只允许这样的代码:
SymbolIndexer & ref_symbol_indexer_ = SymbolIndexer::GetUniqueInstance ( );
发布于 2011-05-21 04:17:18
您可以将复制构造函数设为私有,并且不提供任何实现:
private:
SymbolIndexer(const SymbolIndexer&);
或者在C++11中,明确禁止:
SymbolIndexer(const SymbolIndexer&) = delete;
发布于 2011-05-21 04:16:30
将SymbolIndexer( const SymbolIndexer& )
设置为私有。如果你赋值给一个引用,你不是在复制。
发布于 2021-06-22 22:40:51
学习引用vs指针的C++开发人员可能会想要
class MyClass {
SomeClass acc;
public:
MyClass() : acc() {}
SomeClass &GetAccess( return acc; );
};
作为一种方便的方法:
someblock->{
MyClass inst;
auto acc = inst.GetAccess();
acc.SomeFunction();
}
这将在SomeClass内部产生双重释放的问题,因为默认情况下您最终会得到一个副本……
https://stackoverflow.com/questions/6077143
复制相似问题