If I have the following declaration:
#include <iostream>
#include <string>
class DEMData
{
private:
int bitFldPos;
int bytFldPos;
std::string byteOrder;
std::string desS;
std::string engUnit;
std::string oTag;
std::string valType;
int idx;
public:
DEMData();
DEMData(const DEMData &d);
void SetIndex(int idx);
int GetIndex() const;
void SetValType(const char* valType);
const char* GetValType() const;
void SetOTag(const char* oTag);
const char* GetOTag() const;
void SetEngUnit(const char* engUnit);
const char* GetEngUnit() const;
void SetDesS(const char* desS);
const char* GetDesS() const;
void SetByteOrder(const char* byteOrder);
const char* GetByteOrder() const;
void SetBytFldPos(int bytFldPos);
int GetBytFldPos() const;
void SetBitFldPos(int bitFldPos);
int GetBitFldPos() const;
friend std::ostream &operator<<(std::ostream &stream, DEMData d);
bool operator==(const DEMData &d) c开发者_如何学编程onst;
~DEMData();
};
what code should be in the destructor? Should I "delete" the std::string
fields?
Your destructor only has to destroy the members for which you allocate resources. so no, you don't "delete" strings.
You delete pointers you allocate with new
Your destructor doesn't have to be more than
~DEMData()
{
}
No, the std::string members are allocated automatically on the stack or heap for you and are cleaned up automatically. You do not have to do anything special in your destructor to handle the strings.
No, you should not delete the std::string
objects. they will be automatically freed up when their destructor's gets called.
You don't need a destructor (nor a copy constructor, nor an overloaded assignment operator). That's the whole point of using a class like string that does things for you, rather than going with C-style strings and manual memory management.
The compiler produces all the afore-mentioned for you and by default the destructor just invokes the destructors of all members (this happens implicitly even after a user-defined destructor completes). String's destructor takes over from there.
精彩评论