template < typename ArrayType >
ArrayType *VectorToArray(ArrayType **p_ppThisBlock = NULL, vector<ArrayType> *p_vThisVector = NULL)
{
// Check to see if both parameters are valid.
if(p_ppThisBlock == NULL || p_vThisVector == NULL)
{
return NULL;
}
else if(p_ppThisBlock != NULL && p_vThisVector != NULL)
{
// Create the array that will store the vector's elements dynamically.
p_ppThisBlock = new ArrayType[ p_vThisVector -> size() ];
// Initialize the array.
for(unsigned uIndex(0); uIndex < p_vThisVector -> size(); uIndex++)
{
p_ppThisBlock[ uIndex ] = p_vThisVector[ uIndex ];
}
// Return the pointer that pointing to the new block of memory. Is this relevant?
return p_ppThisBlock;
}
}
我的問題是:是否返回我在此函數中創建的相關內存塊?(第12行)。我應該返回這個內存塊嗎?
噢,我的。你爲什麼做這個?你不能只用`&v [0]`?至少,確保使用智能指針(使用數組刪除器);否則這段代碼肯定不是異常安全的。 – 2011-01-24 23:30:07
除此之外,你寫的甚至不能正常工作:賦值`p_ppThisBlock = new ArrayType [...]`是ArrayType *和ArrayType **之間的不匹配(應該得到編譯器警告在這裏);你想要`* p_ppThisBlock = ...`。同樣在for循環中,你需要`(* p_ppThisBlock)[uIndex] =(* p_vThisVector)[uIndex]`。 – 2011-01-24 23:58:04