此代碼在delete [] placard_上返回錯誤;調用在指向對象的指針上調用delete []時發生BLOCK_TYPE_VALID錯誤
void Protestor::destroy() { //Free's caller Protestor's dynamic memory
delete [] placard_;
}
此代碼不會。
void Protestor::destroy() { //Free's caller Protestor's dynamic memory
delete placard_;
}
這違背了我的課堂筆記,其狀態隨時撥打
delete []
而不是
delete
,這是什麼行爲,如何解釋呢?在什麼情況下必須'刪除'而不是'delete []'?
這裏是抗議者和標誌類的定義。
class Protester
{
public:
Protester(string name, string signSlogan, int signHeight, int signWidth,
int rcmp_file = 0);
string getName() const;
Sign getPlacard() const;
void changePlacard(string newSlogan, int newHeight, int newWidth);
void setRCMPfile(int RCMP_file);
int getRCMPfile() const;
//Big Three
Protester(const Protester& other); //Copy Constructor
~Protester(); //Destructor
Protester& operator= (const Protester& other); //Assignment Constructor
private:
// name of the Protester
string name_;
// a sign the protester is wielding
Sign* placard_;
// the RCMP file number tracking this person (zero means no RCMP report)
int rcmp_file_;
//Big Three Helper Functions
void copy(const Protester& other); //Performs Deep Copy of const Protester&
void destroy(); //deletes [] placard_
//sounds better then cleanup, in my humblest of opinions.
};
class Sign
// a class representing information about signs/placards
{
public:
// constructor to initialize sign text and dimensions
Sign(string statement, int height, int width);
// return sign text
string getStatement() const;
//return sign height
int getHeight() const;
//return sign width
int getWidth() const;
// change sign text
void setStatement(string statement);
// change sign dimensions
void setSize(int height, int width);
private:
// the text of the sign
string statement_;
// dimensions of the sign
int height_;
int width_;
};
我正確地認爲std :: shared/unique_ptr方法是在RIiA的保護下?在課堂以外,我一直在閱讀很多關於這方面的內容,但是恐怕我的助教可能不想在實驗室範圍之外篩選任何代碼。 – 2012-03-02 09:46:23
他們被鏈接是的。如果你因爲實驗室限制而無法使用它們,那就不要這樣做。通常所說的是理想的做法。 – 2012-03-02 10:03:18