gpt4 book ai didi

c++ - 单例类找不到 ctor 但编译、运行并使实例未初始化

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:21:00 24 4
gpt4 key购买 nike

我在 MSVC++ 17 版本 15.5.5 中实现单例模式时遇到问题。我正在编译标志 /std:c++17 .

我的实现包含以下辅助类:

#pragma once
#include <cassert>

template<class T>
class Singleton : private T
{
public:
virtual ~Singleton() = default;

template<typename ... Targs>
static T & initInstance(Targs && ... args)
{
assert(instance == nullptr);
instance = new Singleton<T>(std::forward<Targs>(args)...); //The constructor of T might be inaccessible here so let our own ctor call it
return *instance;
}

static T & getInstance()
{
assert(instance != nullptr);
return *instance;
}

private:
template<typename ... Targs>
explicit Singleton(Targs && ... args)
: T{ std::forward<Targs>(args)... }
{}

static T * instance;
};

template<class T>
T * Singleton<T>::instance = nullptr;

此实现的一个目标是具有某种形式的惰性初始化,但没有多余的 if每次执行的语句 getInstance()叫做。只有第一次才有用,因为实例需要初始化,但之后 if只是开销。为此,我创建了函数 initInstance()你必须先打电话才能打电话getInstance() .我很清楚 assert()仅在 Debug模式下工作,但这对我的项目来说很好。

该类旨在按以下方式使用:

#include "Singleton.h"
#include <iostream>
class Foo
{
public:
virtual ~Foo() = default;

protected: //has no public ctor's
Foo(int i) //has no default ctor
: i{ i }
{
std::cout << "foo ctr " << i << "\n"; //Not printed if no ctor of Foo is found
}

private:
int i;
};

int main(int argc, char** argv)
{
Singleton<Foo>::initInstance(5); //Selects and executes Foo(int i).
//Singleton<Foo>::initInstance(); //Should not compile, yet it does. Calls no ctor of Foo at all.
Foo & theOnlyFoo = Singleton<Foo>::getInstance(); //or just use the return value of initInstance(5) to initialize this reference

//...
return 0;
}

问题:

如果我调用 Singleton<Foo>::initInstance();没有任何论据,即使Foo没有默认构造函数,代码仍然可以编译和运行。我本来期望实例化 Singleton<Foo> 的构造函数会失败,因为它调用 Foo具有给定参数的构造函数,但在查找时它不应该能够找到合适的构造函数。然而代码以某种方式编译。

当我执行代码时 Singleton<Foo> 的构造函数被调用但是 Foo 的构造函数本身不是。当我在 instance 之后的断点处停止执行时已初始化并检查其数据成员的值 i它是一些随机的巨大负值,表明根本没有执行任何代码来初始化 Foo 的实例。 .

只有在 Foo 没有合适的构造函数时才会发生这种情况。打电话。如果有,一切正常,Foo调用选定的构造函数。

最佳答案

正如评论中所建议的,这可能是一个编译器错误。我提交了错误报告。

我还针对我在评论中描述的内部编译器错误提交了错误报告。当我(错误地)输入 using T::T; 时发生内部编译器错误在 Singleton<T>::InitInstance()然后调用T s 构造函数。

关于c++ - 单例类找不到 ctor 但编译、运行并使实例未初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49070263/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com