Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Visual C++ 6 complains on private destructor

Tags:

c++

The following code works fine for Visual C++ 2008. However, when comes to Visual C++ 6, I get the following error. May I know why, and how I can fix the error, but still make the destructor remains in 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 private member declared in class 'X' C:\Projects\ttt6\main.cpp(175) : see declaration of 'X::~X'

like image 220
Cheok Yan Cheng Avatar asked Feb 26 '10 05:02

Cheok Yan Cheng


People also ask

What happens if destructor is private in C++?

Destructors with the access modifier as private are known as Private Destructors. Whenever we want to prevent the destruction of an object, we can make the destructor private. What is the use of private destructor? Whenever we want to control the destruction of objects of a class, we make the destructor private.

Can destructor be private in Java?

Basically, any time you want some other class to be responsible for the life cycle of your class' objects, or you have reason to prevent the destruction of an object, you can make the destructor private.

Is destructor public?

If no user-declared prospective (since C++20) destructor is provided for a class type (struct, class, or union), the compiler will always declare a destructor as an inline public member of its class.


3 Answers

The revised sample shows a confirmed compiler bug for VC6 - the common workaround was to simply make the destructor public.

like image 139
Georg Fritzsche Avatar answered Nov 12 '22 13:11

Georg Fritzsche


In fun() you are creating a separate object, aa and then copying the value of the object reference returned by a::instance() to it via the assignment operator. This won't work because both constructor and destructor are private. aa should be a reference:

a &aa = a::instance();
like image 24
Aaron Klotz Avatar answered Nov 12 '22 12:11

Aaron Klotz


When the end of fun() is reached, your variable will go out of scope and the destructor will be called.

It looks like you're trying to implement a singleton - perhaps you mean this?

a& aa = a::instance();

If aa is a reference rather than an instance then the destructor won't be called at the end of fun().

like image 2
andrewffff Avatar answered Nov 12 '22 11:11

andrewffff