This Code returns an error on the delete [] placard_; call
void Protestor::destroy() { //Free's caller Protestor's dynamic memory
delete [] placard_;
}
This code does not.
void Protestor::destroy() { //Free's caller Protestor's dynamic memory
delete placard_;
}
This goes against my class notes, which state to ALWAYS call
delete []
rather than
delete
What is the explanation for this behaviour? Under what conditions must ‘delete’ be called instead of ‘delete []’?
Here is the Definition for the Protester and Sign classes.
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_;
};
No that’s wrong. You have to pair calls to
newanddeleteand calls tonew[]anddelete[].Note:
But that’s not how you should to that in modern C++. Use
std::shared_ptrorstd::unique_ptrinstead. This is usually a much safer choice. Calls tonew/new[]should be nearly always enclosed in smart pointer anddeleteshould not be needed at all. Very few exceptions.