- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我在 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/
我最近购买了《C 编程语言》并尝试了 Ex 1-8这是代码 #include #include #include /* * */ int main() { int nl,nt,nb;
早上好!我有一个变量“var”,可能为 0。我检查该变量是否为空,如果不是,我将该变量保存在 php session 中,然后调用另一个页面。在这个新页面中,我检查我创建的 session 是否为空,
我正在努力完成 Learn Python the Hard Way ex.25,但我无法理解某些事情。这是脚本: def break_words(stuff): """this functio
我是一名优秀的程序员,十分优秀!