问题描述
我在代码中发现这个我正在维护
模板< class SingletonClass>
SingletonClass * Singleton< SingletonClass> :: instance()
{
静态SingletonClass _instance;
return& _instance;
}
有迹象表明构造函数在某些情况下被调用超过
(跟踪在
模板的一个实例中。
使用静态数据是否存在潜在问题?
- -
Nick Keighley
有时候,这个
代码没有任何内在错误(但你可能会考虑使用引用)。请参阅
_Modern C ++ Design_的第6章,比你想知道的更多
关于C ++中的单身人士。
干杯! --M
使用Visual C ++ 6.0时我遇到了这个问题。但是在发布模式下只有
,而不是在调试模式下。可能是优化器的问题是什么?$!$
解决方案是移动实例的实现()
.h从.h到.cpp文件的方法。
希望它有所帮助...
Tilman
有时候,这个
代码没有任何内在错误(但你可能会考虑使用引用)。请参阅
_Modern C ++ Design_的第6章,比你想知道的更多
关于C ++中的单身人士
..
谢谢,我继续留意MCD的意思,但我不是
舒适的模板。
比如这样的事情: -
class PerformanceDataItemIniFile:public PanelIniFile,
public Singleton< PerformanceDataItemIniFile>
...
让我担心它继承自使用自身作为参数的东西。
-
Nick Keighley
Hi,
I found this in code I was maintaining
template <class SingletonClass>
SingletonClass* Singleton<SingletonClass>::instance ()
{
static SingletonClass _instance;
return &_instance;
}
there are indications that the constructor is getting called more than
once
in some circumstances (tracing in one of the instantiations of the
template).
Are there potential problems with the use of static data?
--
Nick Keighley
There are sometimes, but there''s nothing inherently wrong with this
code (you might consider using references instead, however). See
chapter 6 of _Modern C++ Design_ for more than you ever wanted to know
about singletons in C++.
Cheers! --M
I had exactly this problem when using Visual C++ 6.0. But only
in Release mode, not in Debug mode. Perhaps a problem with
the optimizer...?!
The solution was to move the implementation of the instance()
method from the .h to the .cpp file.
Hope it helps...
Tilman
There are sometimes, but there''s nothing inherently wrong with this
code (you might consider using references instead, however). See
chapter 6 of _Modern C++ Design_ for more than you ever wanted to know
about singletons in C++
..
thanks, I keep on meaning to getting around to MCD, but I am not
comfortable with templates.
For instance something like this:-
class PerformanceDataItemIniFile : public PanelIniFile,
public Singleton< PerformanceDataItemIniFile >
...
worries me it inherits from something that uses itself as a parameter.
--
Nick Keighley
这篇关于单身模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!