我有以下代码
#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);
}
根据许多建议,析构函数是私有的,只能在程序结束时调用一次。
但我有编译器错误:
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
当然,我可以公开构造函数和/或析构函数,并且没有任何类似的错误。但我需要确保它们都被调用一次且仅调用一次。
如何?