构造函数内的静态变量有什么缺点或副作用吗?
我想要做的:只要在程序中使用类的实例,就运行一些先决条件代码。该代码将检查需求等,并且应该只运行一次。
我发现可以使用另一个对象作为构造函数内的静态变量来实现这一点。下面是一个更好的例子:
class Prerequisites
{
public:
Prerequisites() {
std::cout << "checking requirements of C, ";
std::cout << "registering C in dictionary, etc." << std::endl;
}
};
class C
{
public:
C() {
static Prerequisites prerequisites;
std::cout << "normal initialization of C object" << std::endl;
}
};
令我困扰的是,到目前为止我还没有看到静态变量的类似用法。有什么缺点或副作用吗?或者我错过了什么?或者也许有更好的解决方案?欢迎任何建议。
What I want to do: run some prerequisite code whenever instance of the class is going to be used inside a program. This code will check for requiremts etc. and should be run only once.
I found that this can be achieved using another object as static variable inside a constructor. Here's an example for a better picture:
class Prerequisites
{
public:
Prerequisites() {
std::cout << "checking requirements of C, ";
std::cout << "registering C in dictionary, etc." << std::endl;
}
};
class C
{
public:
C() {
static Prerequisites prerequisites;
std::cout << "normal initialization of C object" << std::endl;
}
};
What bothers me is that I haven't seen similar use of static variables so far. Are there any drawbacks or side-effects or am I missing something? Or maybe there is a better solution? Any suggestions are welcome.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这不是线程安全的,因为如果两个线程尝试同时第一次构造 C,则先决条件可能会被初始化两次。
如果你同意这一点,你可能可以这样做,尽管玩范围构造函数系统的可发现性为零(即一旦你忘记了“技巧”或其他人尝试阅读你的代码,他们会对发生的事情感到困惑)。
This isn't thread-safe, since if two threads try to construct C for the first time at the same time, Prerequisites will probably be initialized twice.
If you're okay with that, you can probably do this, though gaming the scoped constructor system has zero discoverability (i.e. once you forget the 'trick' or others try to read your code, they'll be baffled as to what's going on).
显式调用静态方法可能会更清晰(尽管更冗长)。
It might be clearer (though more verbose) to explicitly invoke a static method.
您至少应该在先决条件类中使用互斥锁和静态标志来防止先决条件对象的多次初始化。这样你的代码将变得线程安全。
You should at least use a mutex and a static flag inside Prerequisites class to protect agains multiple initialization of Prerequisites objects. In that way your code will become thread safe.