在函数内定义静态对象是正确的方法吗?
class MyClass {
public:
static MyClass& getInstance() {
static MyClass obj;
return obj;
}
};
int main()
{
MyClass& obj1 = MyClass::getInstance();
MyClass& obj2 = MyClass::getInstance();
|
|
MyClass& obj1000 = MyClass::getInstance();
}
如果多次调用 getInstance() 函数,它是否总是返回相同的对象,并且所有 obj1、obj2 ... obj1000 将引用相同的对象。
class MyClass {
public:
static MyClass& getInstance() {
static MyClass obj;
return obj;
}
};
int main()
{
MyClass& obj1 = MyClass::getInstance();
MyClass& obj2 = MyClass::getInstance();
|
|
MyClass& obj1000 = MyClass::getInstance();
}
If several times getInstance() function is called, Will it always return the same object and all obj1, obj2 ... obj1000 will refer the same object.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,这是一种有效的方法,并且所有 objXXX 都将引用同一个对象。该对象将在第一次调用该函数时构造。
Yes, this is a valid approach and yes, all of objXXX will refer to the same object. The object will be constructed the first time the function is called.
是的,但要注意线程问题。如果您在启动将调用该方法的任何其他线程之前不调用
getInstance()
,则此代码会受到竞争条件的影响。Yes, but beware threading issues. This code is subject to race conditions, if you do not call
getInstance()
before you start any other thread that will call the method.从技术上讲,这是合法的 C++,并且您将始终获得相同的对象。它被称为单例反模式,应该像瘟疫一样避免,因为它会产生可怕的难以维护的软件。这是正确的方法吗?绝对不是。
Technically, this is legal C++ and you will always get the same object. It's known as the Singleton anti-pattern and should be avoided like the plague, because it produces horrendously unmaintainable software. Is it the right approach? Most definitely not.