2013-10-27 223 views
0

我有一個循環,它增加了指向矢量的指針;使用矢量指針指向對象的指針C++

vector<Material *> materials; 

和我的材料類有4個屬性:

int id; 
float *ambiance; 
float *diffuse; 
在我的循環

while(input_read_from_the_file !=NULL){ 
int id=someval1; 
float x[2]={someval2,someval3}; 
float y[2]={someval4,someval5}; 
materials.push_back(new Material(id,x,y)); 
} 

當我看到我的材料載體在for循環中我看到,ID是不同的,但氛圍和漫反射對於所有元素都是一樣的。這可能是因爲它在while循環中使用了相同的指針,但是我找不到替代方法。在這裏最好的方法是什麼? 謝謝

+5

你的指針指向是本地的,而循環變量。這是未定義的行爲。爲什麼不存儲數組或向量而不是指針? – juanchopanza

+0

我應該在我的班級中使用數組而不是指針嗎? 而不是浮動*氛圍;浮動氛圍[3]; – Emrah

+1

@Emrah是否有一個合理的* *已知的*固定數量的你會瘋了*不*將它們存儲爲一個聲明的數組。如果是這種情況,則不需要動態存儲它們。如果有這種需求,請改用矢量。 – WhozCraig

回答

1

我儘量避免指針盡我所能。 讓我們從你的矢量開始吧。爲什麼它需要是vector<Material*>而不是vector<Material>? 除非Material是繼承類,否則可以使用Material對象的向量而不是指針。 這樣,你不需要具有vector<Material*>的類的析構函數來迭代和銷燬它們中的每一個(通過使用shared_ptr,你也可以避免這種情況)。

現在,正如評論中提到的那樣,問題是Material使用指針來指定ambiancediffuse成員。沒有理由。 從技術上講,當您正在編寫渲染器或素材系統時,您希望它是Vector3Vector4,但是可以使用float[2]代替。

C++ 11(0x)具有很酷的移動語義,您可以使用它來避免創建臨時對象(因爲我們要將對象推入向量中並且沒有移動語義,所以會創建一個臨時對象而這樣做)

所以,代碼如下:

class Material { 
int id; 
float ambiance[2]; // you really ought to use Vector2 instead. pointers are evil. 
float diffuse[2]; 

Material (const int _id, const float _amb[], const float _dif[]) : id(_id) { 
    ambiance[0] = _amb[0]; ambiance[1] = _amb[1]; // actual copy is made 
    diffuse[0] = _dif[0]; diffuse[1] = _dif[1]; 
} 
} 

----- 
vector<Material> materials; 

while(input_read_from_the_file !=NULL){ 
    int id = someval1; 
    float x[2]= {someval2,someval3}; 
    float y[2]= {someval4,someval5}; 
    materials.emplace_back(Material(id,x,y)); // or even materials.emplace_back(id, x, y); 
}