我有以下代碼需要確保構造函數/析構函數被調用一次。但「錯誤:析構函數是私有的」
#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
事業,我可以構造和/或析構函數的公共和沒有類似的錯誤。但是我需要確定他們兩次只被調用過一次。
如何?
@alestanis它是一個單例。 'getInstance()'被稱爲'getA()'。 – juanchopanza
@OlegG你的單例實例在堆上分配(使用'new'),但從未釋放。你爲什麼不把它分配給堆棧? – jogojapan
有一個關於如何在C++中實現單例模式的問題,在這裏有很多很好的答案:http://stackoverflow.com/questions/1008019/c-singleton-design-pattern – jogojapan