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'
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.
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.
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.
The revised sample shows a confirmed compiler bug for VC6 - the common workaround was to simply make the destructor public.
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();
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().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With