gpt4 book ai didi

c++ - 在指向对象的指针上调用 delete [] 时出现 BLOCK_TYPE_VALID 错误

转载 作者:行者123 更新时间:2023-11-28 00:59:30 24 4
gpt4 key购买 nike

此代码在 delete [] placard_ 上返回错误;打电话

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' 而不是 'delete []'?

这是 Protester 和 Sign 类的定义。

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_;
};

最佳答案

This goes against my class notes, which state to ALWAYS call delete [] rather than delete

不,那是错误的。您必须配对调用 newdelete 以及调用 new[]delete[]

注意:但在现代 C++ 中,您不应该这样做。请改用 std::shared_ptrstd::unique_ptr。这通常是一个更安全的选择。对 new/new[] 的调用应该几乎总是包含在智能指针中,并且根本不需要 delete。很少有异常(exception)。

关于c++ - 在指向对象的指针上调用 delete [] 时出现 BLOCK_TYPE_VALID 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9530834/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com