2014-09-28 123 views
0

當我在堆上聲明數組時,哪種方法更好?爲了簡單和例子的緣故,私人數據在這裏公開。在堆上聲明數組

我應該創建一個新的指針,修改數據,然後

CAT *Family = new CAT[2]; 

for(int i=0; i<2;i++){ 
    Family[i].age = i+1; 
} 

VS

CAT *Family = new CAT[2]; 
CAT *pCat; 


for(int i=0; i<2;i++){ 
    pCat = new CAT; 
    pCat->age = i+1; 
    Family[i] = *pCat; 
    delete pCat; 
} 
+1

第二種方法似乎在第一種方法上沒有優勢,而且更復雜。 – Beta 2014-09-28 04:24:01

+0

你有什麼理由相信第二種方法有什麼優勢嗎? – 2014-09-28 04:35:10

+0

@RSahu不,我使用第一種方法。但我在一個例子中看到了第二個。只是好奇。 – 2014-09-28 04:36:19

回答

0

你的第二個執行會分配在堆棧上更多的變量,將需要更多的複雜的彙編代碼(我記得不得不爲C風格語言的上述代碼生成彙編代碼,並且它變得很難受!)。對於獎勵積分,如果你正在尋找優化,我建議你使用pre-increment in your for loop;)

2

這通常不是一個好主意,直​​接使用原始指針和new

越少越好。

相反,以創建在堆上陣列,這樣做:

std::vector<Cat> cats(2); 
for(int i = 0; i < int(cats.size()); ++i){ 
    cats[i].age = i+1; 
} 

或可替代地,這樣的:

std::vector<Cat> cats; 
for(int i = 0; i < 2; ++i){ 
    cats.emplace_back(i+1); 
} 

直接使用原始陣列和new的表示一個C程序員或無能,因爲std::vector正是爲了這個目的而在C++標準庫中,所以要注意正確的內存管理。


還要注意,ALL UPPERCASE名稱是用於宏的慣例。這個想法是爲了儘量減少名稱衝突和無意文本替換的機會。當您將這些名稱用於其他事情時,您反而會增加名稱衝突和無意文本替換的機會,更不用說許多程序員將大寫字母看作是大聲喊話或強調重點。

1

第一種方法在調用構造函數的次數方面具有確定的優勢。對於你的微不足道的例子來說,它很好。但是,假設一個類在c'tor中進行了大量資源分配並將其釋放。 第二種方法將這些c'tors和d'tor額外2次這是一個重罰。 #include using namespace std;

class CAT{ 
public: 
CAT(){ cout<<"c'tor called"<<endl;} 
int age; 
~CAT(){ cout<<"d'tor called"<<endl;} 
}; 

main(){ 
    CAT *Family= new CAT[2]; 
    CAT *pCat; 

    for(int i=0; i<2;i++){ 
    pCat = new CAT; 
    pCat->age = i+1; 
    Family[i] = *pCat; 
    delete pCat; 
    } 
} 

Run it 

$./a.out 
c'tor called 
c'tor called 
c'tor called 
d'tor called 
c'tor called 
d'tor called 
0

如果您嘗試創建對象數組,則看不到第一個方法的優點。但是,如果您嘗試創建指向數組的指針數組,則可能需要使用第二種方法,這可能指向不同的具體類型。

struct A 
{ 
    virtual ~A() {} 
}; 

struct B : A 
{ 
    int data; 
} 

struct C : A 
{ 
    double data; 
} 


int main() 
{ 
    A* array[20]; 

    // Get half of the array filled with B*. 
    for (int i = 0; i < 10; ++i) 
    { 
     B* b = new B; 
     b.data = i*10; 
     array[i] = b; 
    } 

    // Get the other half of the array filled with C*. 
    for (int i = 10; i < 20; ++i) 
    { 
     C* c = new C; 
     c.data = i*1.5; 
     array[i] = c; 
    } 

    // Delete the objects. 
    for (int i = 0; i < 20; ++i) 
    { 
     delete array[i]; 
    } 

    return 0; 
}