2016-07-21 48 views
0

讓我們以下面的類例如哪裏(哪些內存段)是存儲在C++中的對象(類的)?

class Shape{ 
    public: 
     Circle (int x): number(x){} 
     virtual area() {return x**2;} 

    private: 
     int number; 
} 

在主,我們創建對象

int main(){ 
    Shape *foo = new Shape(8); 
    Shape *bar = new Shape(65); 
    Shape &obj1 = *foo, &obj2 = *bar; 
} 

相信的對象1和2都存儲在堆上。這是爲什麼? 作爲一個側面的問題。虛擬關鍵字或/和對象的定義方式(例如obj1 = * foo)是否會影響其在內存中的位置?

+9

'foo'和'bar'具有動態存儲持續時間,並存儲在* freestore *中。 C++語言規範沒有提到*「heap」*作爲存儲。 'obj1'和'obj2'是**引用**。它們是現有對象的別名,僅在編譯期間存在(如所有變量)。它們(通常)不會反映在可執行映像或運行時的內存中。 – IInspectable

+0

參考:http://stackoverflow.com/questions/10157122/object-creation-on-the-stack-heap –

回答

0

有(廣義上)兩種類型的對象W.R.T.他們的存儲器管理:

  1. 的對象可以在編譯時期間被完全構造
  2. 一個對象只能使用的一些信息是不可用的程序運行

後例如直到被完全構造,任何constexpr類型的對象可以在編譯期間完全評估和構建,並且因此可以作爲優化放置到內存數據段中(從純化的角度來看,在運行期間構建這樣的對象是有效的但遠非最佳的這會浪費CPU週期並進行初始化/啓動更長)。

這裏有這樣的對象的幾個例子:

const char * const helloWorld = "Hello, world!"; 
struct TSilly{ 
    TSilly(int _i = 0) : i(_i) {} 
    int i; 
}; 
const TSilly silly1; 
const TSilly silly2(42); 
TSilly silly3; // doesn't have to be constexpr to qualify for static allocation. 
       // This one you can declare as /*extern TSilly silly3;*/ in 
       // header file and access from other compilation units 
static TSilly silly4; // can be local to compilation unit, too 

int main() 
{ 
    return 0; 
} 

所有其他對象將不得不等待,直到要構建的運行時間。這種物體的

實例:

const char * exeName1; // statically allocated by compiler 

int main(int argc, char **argv) 
{ 
    exeName1 = argv[0]; // now points to a string 

    // buffer is allocated in free storage (heap) bu variable itself is on stack 
    char * exeName2 = new char[strlen(argv[0] + 1]; 
    strcpy(exeName2, argv[0]); // now contains a COPY of a string 

    char exeName3[1024]; // likely allocated on stack, be careful with that as stack space is limited 
    strncpy(exeName3, argv[0], 1024); // will COPY at most 1023 characters from a string 

    delete [] exeName2; // don't forget to clean up 
    // exename3 will be auto-cleaned when we exit the function 

    return 0; 
} 

正如你可以看到在C++的對象將被放入一個數據段或成根據其壽命的自由存儲(堆)。

只有動態分配的對象才能保證進入空閒存儲。我不認爲該規範使得數據段的靜態分配對象使用的任何承諾 - 它是由編譯器執行和利用最優化。

欲瞭解更多信息護目鏡「C++存儲類」。

有許多先進的內存管理主題可能需要考慮。與本次討論最相關的一個可能是就地構造函數,它允許您在分配給可執行文件數據段的內存中構建運行時對象。

+0

在我的例子是什麼渲染的對象動態分配? –

+0

你是什麼意思?你能不同地問你的問題嗎? – YePhIcK