2017-08-24 39 views
1

我可以聲明靜態數據成員在C++中使用新的? 如果我們可以用new聲明靜態數據成員,那麼如何初始化那個靜態數據成員?靜態成員變量與新運營商類

class A 
{ 
    static int *p = new int;  
} 

int * A :: p = 
+0

聲明變量內聯在類中,定義和初始化之外的類。這是最簡單的。 –

+0

這很好,但我的問題是我可以聲明靜態變量在類中使用新的 –

+0

不,不這麼認爲..靜態值不駐留在堆中 –

回答

3

要走的路是聲明類內部的變量和初始化它在它之外:

class A { 
public: 
    static int* anIntPointer; //<- declaration 
}; 

int* A::anIntPointer = new int(42); //<- initialisation 

但是你仍然需要手動清理內存,因爲當程序只結束指針被刪除,但它指向的內存仍然保留(除非你的操作系統跟蹤內存並在程序結束後清理)。所以請致電delete A::anIntPointer,例如在main的末尾。

如果您確實可以訪問C++ 17,但是您可以聲明可以直接初始化的成員inline

class A { 
public: 
    inline static int* anIntPointer = new int(42); //<- declaration + initialisation 
}; 

無論如何,如果你不想對自己負責清理內存,你可以使用智能指針(std::auto_ptr<>之前C++ 11,std::unique_ptr<> C++ 11起)。

class A { 
public: 
    static std::unique_ptr<int> anSmartPointer; 
}; 

std::unique_ptr<int> A::anSmartPointer = std::unique_ptr<int>(new int(42)); // C++11 
// std::unique_ptr<int> A::anSmartPointer = std::make_unique<int>(42); // or C++14 style 

A::anSmartPointer將在程序結束時把它毀了清理它自動地控制內存。

Here你可以看到我剛剛解釋過的所有東西以及其他一些東西(如C++ 17 inline static智能指針)的工作示例。

+0

如果它是C++ 11或更高版本,聽起來像是'std :: unique_ptr <>'的一個工作,如果早些時候咬緊牙關並使用'std :: auto_ptr <>'或推出自己的。 – Persixty

+0

這裏指針是靜態變量,它指向的數據在堆上,對吧? – Viktor

+1

@Viktor正確。 – muXXmit2X