2017-02-24 31 views
-1

我有一個稱爲shape和一些派生類(如circle,rectangle,poly(最大8點))的類。更改在程序啓動時預先分配的Dymanic內存分配

一個_Point結構包含x和y座標。

因此,對於圓,它包含一個_Point和半徑;矩形包含2個_Point和Poly包含8個_Point。

每次創建對象時,都會使用new來分配內存,並且在更改/編輯爲不同的形狀類型時,將會刪除內存,釋放內存併爲新形狀分配新內存。

這將導致碎片,因爲我在嵌入式系統上使用它。 因此,我想在程序開始使用新的最大形狀(例如聚合物的10個副本,10個用戶可以創建的最大形狀)時預先分配內存,並且當用戶爲第三個項目創建一個圓形時,我會只是簡單地說明特定的內存塊。這可行嗎? C++能接受類似普通C的類型轉換,以及如何在C++中實現。內存將僅在程序結束時釋放。

謝謝。

+2

您可以使用placement new來使用預先分配的內存塊。 –

+1

我相信使用「C++自定義內存分配器」選擇的搜索引擎將爲您提供足夠的文獻和示例,以便開始使用 – UnholySheep

+0

您好,請參閱[tour](http://stackoverflow.com/tour)並閱讀[幫助頁面](http://stackoverflow.com/help)。 – 2017-02-24 10:56:31

回答

-1

不是一個乾淨的設計,而只是你想要做的一點暗示。想法是在Base類中保留所有可能的Shapes的所有數據需求,並使用派生類實現取決於Shape類型的行爲。

struct _Point 
{ 
    float x, y; 
}; 

class Data 
{ 
    protected: 
     _Point points[8]; //max 8 as required. 
}; 

class Behaviour_1 : public Data 
{ 
    public: 
    void Set(_Point x, _Point y) 
    { 
     points[0] = x; 
     points[1] = y; 
    } 
    void Draw() 
    { 
     //use points[0] and points[1] 
     cout << "Drawing Line ----" << endl; 
     cout << "X coordinates: " << points[0].x << ", " << points[0].y << endl; 
     cout << "Y coordinates: " << points[1].x << ", " << points[1].y << endl; 
    } 
}; 

class Behaviour_2 : public Data 
{ 
    public: 
    void Set(_Point x, float radius) 
    { 
     points[0] = x; 
     points[1].x = radius; 
    } 

    void Draw() 
    { 
     //use points[0] and points[1].x 
     cout << "Drawing Circle ----" << endl; 
     cout << "Center coordinates: " << points[0].x << ", " << points[0].y << endl; 
     cout << "Radius : " << points[0].x << endl; 
    } 
}; 

int main() 
{ 
    // your code goes here 
    _Point x = {10, 20}; 
    _Point y = {30, 50}; 
    float radius = 60.0f; 

    Data shape; 
    Behaviour_1 *Line = (Behaviour_1 *)(&shape); 
    Line->Set(x, y); 
    Line->Draw(); 

    Behaviour_2 *Cicle = (Behaviour_2 *)(&shape); 
    Cicle->Set(x, radius); 
    Cicle->Draw(); 

    return 0; 
} 

Output: 
Drawing Line ---- 
X coordinates: 10, 20 
Y coordinates: 30, 50 
Drawing Circle ---- 
Center coordinates: 10, 20 
Radius : 10 

在上述類:

  • Data可以是具有Shape所有任何種Shape所需的必要的數據。
  • Behaviour_1可以是Line,僅使用points[0] and points[1]作爲其終點。
  • Behaviour_2可以是Circle,以points[0]爲中心,points[1].x爲半徑。
+0

這真的很糟糕。 upcasts是UB(如果你需要任何子類中的成員,它將會真正破壞),你在每個非多邊形中浪費了一堆點。 – Caleth

+0

@Caleth:已經提到只有行爲纔會由派生類實現,而這些派生類不會擁有任何自己的數據。所有的數據需求都將在基類中。 – sameerkn

+0

upcasts仍未定義。符合標準的編譯器可以在你的例子中完成任何事情。 – Caleth