如何调用静态对象的私有析构函数? [英] How are the private destructors of static objects called?

查看:465
本文介绍了如何调用静态对象的私有析构函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

无法访问单例类析构函数中的私有成员


我正在实现下面的单例。

  class A 
{
public:

static A& instance();
private:
A(void)
{
cout< 在构造函数< endl;
}
〜A(void)
{
cout< 在析构函数中< endl;
}

};

A& A :: instance()
{
static A theMainInstance;
return theMainInstance;
}

int main()
{
A& a = A :: instance();

return 0;
}

析构函数是私有的



我试过这个在Visual Studio 6,它给出了编译错误。

 无法访问在类中声明的私有成员...

在visual studio 2010中,这个已经编译,析构函数



期望在这里根据标准?



编辑:混乱出现,因为Visual Studio 6的行为不是那么蠢。可以说,A的静态对象的构造函数在A的函数的上下文中被调用。但是析构函数在相同函数的上下文中不被调用。

解决方案

C ++ 03标准的第3.6.3.2节说:



静态存储持续时间的初始化对象(在块范围或命名空间范围声明)的析构函数称为从main返回的结果,退出。



它没有给任何限制关于有一个私有析构函数,所以基本上如果它被创建它也将被销毁。 / p>

私有析构器对声明对象的能力造成限制(C ++ 03 12.4.10)



如果类类型或其数组的对象被声明,并且类的析构函数在声明点不可访问,则程序是错误的



但是因为A :: theMainInstance的析构函数在声明的时候是可访问的,你的例子应该没​​有错误。


Possible Duplicate:
Cannot access private member in singleton class destructor

I'm implementing a singleton as below.

class A
{
public:

    static A& instance();
private:
    A(void)
    {
        cout << "In the constructor" << endl;
    }
    ~A(void)
    {
        cout << "In the destructor" << endl;
    }

};

A& A::instance()
{
    static A theMainInstance;
    return theMainInstance;
}

int main()
{
    A& a = A::instance();

    return 0;
 }

The destructor is private. Will this get called for the object theMainInstance when the program is about to terminate?

I tried this in Visual studio 6, it gave a compilation error.

"cannot access private member declared in class..."

In visual studio 2010, this got compiled and the destructor was called.

What should be the expectation here according to the standard?

Edit : The confusion arises since Visual Studio 6 behaviour is not so dumb. It can be argued that the constructor of A for the static object is called in the context of a function of A. But the destructor is not called in the context of the same function. This is called from a global context.

解决方案

Section 3.6.3.2 of the C++03 standard says:

Destructors for initialized objects of static storage duration (declared at block scope or at namespace scope) are called as a result of returning from main and as a result of calling exit.

It doesn't give any restriction regarding having a private destructor, so basically if it gets created it will also get destroyed.

A private destructor does cause a restriction on the ability to declare an object (C++03 12.4.10)

A program is ill-formed if an object of class type or array thereof is declared and the destructor for the class is not accessible at the point of declaration

but since the destructor of A::theMainInstance is accessible at the point of declaration, your example should have no error.

这篇关于如何调用静态对象的私有析构函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆