我有以下问题。我有一个带有getInstance成员函数的单例,它返回一个实例。我在代码中调用它,由于某种原因,VC尝试调用复制构造函数。为什么是这样?我该如何解决这个问题?
标题:
class FileSystemEntryCollection {
public:
static FileSystemEntryCollection &getInstance();
private:
FileSystemEntryCollection();
FileSystemEntryCollection(FileSystemEntryCollection const&);
void operator=(FileSystemEntryCollection const&);
}
源文件:
FileSystemEntryCollection &FileSystemEntryCollection::getInstance() {
static FileSystemEntryCollection instance = FileSystemEntryCollection();
return instance;
}
以下行调用复制构造函数:
auto collection = FileSystemEntryCollection::getInstance();
我试图留下相关代码,如果需要别的东西,请告诉我。
答案 0 :(得分:5)
auto collection = FileSystemEntryCollection::getInstance();
需要:
auto& collection = FileSystemEntryCollection::getInstance();
^
auto
本身永远不是引用类型。
答案 1 :(得分:3)
使用不同的编译器,您将在初始化instance
时收到相同的错误。
static FileSystemEntryCollection instance = FileSystemEntryCollection();
此处=
调用复制构造:正式地,编译器创建临时(FileSystemEntryCollection()
),并将其复制到instance
。但是,在这种情况下,允许编译器跳过复制构造并直接构造对象。这就是你的编译器正在做的事情。但编译器不需要这样做。
更好:
static FileSystemEntryCollection instance;
使用默认构造函数创建instance
。
答案 2 :(得分:0)
它在构造静态单例对象的源文件中调用一次复制构造函数。