I have the following code
#include <vector>
#include <iostream>
class A{
private:
std::vector<int> x;
A(){
// here is a code to open and initialize several devices
// it is allowed to be called once only!!!
std::cout << "constructor called" << std::endl;
};
virtual ~A(){
// here is a code to close several devices
// it is allowed to be called once only!!!
std::cout << "destructor called" << std::endl;
};
public:
static A & getA(){
static A* singleton = new A;
std::cout << "singleton got" << std::endl;
return *singleton;
};
};
int main(int argc, char** argv){
A a = A::getA();
return(0);
}
According to many recommendations the destructor is private to be called once only at end of program.
But i have the compiler error:
Test.cpp: In function 'int main(int, char**)':
Test.cpp:12:10: error: 'virtual A::~A()' is private
Test.cpp:29:19: error: within this context
Test.cpp:12:10: error: 'virtual A::~A()' is private
Test.cpp:29:19: error: within this context
Of cause, I can make constructor and/or destructor public and have no any errors like that. But I need to be sure that both of them are called once and only once.
How?