Why Visual C ++ 6 complains about a private destructor

The following code is great for Visual C ++ 2008. However, when it comes to Visual C ++ 6, I get the following error. Can I find out why, and how can I fix the error, but still make the destructor remains private.

class X
{
public:
    static X& instance()
    {
        static X database;
        return database;
    }

private:

    X() {}                    // Private constructor
    ~X() {}                   // Private destructor
    X(const X&);              // Prevent copy-construction
    X& operator=(const X&);   // Prevent assignment
};

int main()
{
    X::instance();
}

C: \ Projects \ ttt6 \ main.cpp (178): error C2248: 'X :: ~ X': cannot access the private member declared in the class 'X' C: \ Projects \ ttt6 \ main.cpp ( 175): see Declaration "X :: ~ X"

+5
source share
4 answers

The revised example shows a confirmed compiler error for VC6 — a common workaround was to simply make the destructor public.

+7
source

fun() aa, , a::instance(), . , , . aa :

a &aa = a::instance();
+4

fun(), .

, - , ?

& ; aa = a:: instance();

aa , , fun().

+2

This is just a VC6 bug. VC6 is very buggy. You can use std :: auto_ptr <> as a workaround.

#include <memory>

class X
{
    friend std::auto_ptr<X>;
public:
    static X& instance()
    {
        static std::auto_ptr<X> database(new X);
        return *database;
    }
.....
};

And please move the instance () implementation to the cpp file. Unfortunately, I do not remember the exact case, but there is another VC6 error with the implementation of singleton in the header files. A few years ago, we had several crashes when using VC6. The fix was to move instance () implmenetation to cpp.

0
source

All Articles