tags:

views:

253

answers:

4

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) const;
    ~DEMData();
};

what code should be in the destructor? Should I "delete" the std::string fields?

+3  A: 

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.

gbrandt
On the stack? Only if the `DEMData` instance is on the stack.
Daniel Earwicker
Strictly speaking, you can't say if the std::string object itself is on the stack or the heap since you don't know how DEMData is being constructed. The contained string will be on the heap unless the implementation of std::string uses the std::string object itself to store the string for short strings.
Torlack
+10  A: 

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()
{
}
Liz Albin
in fact you can leave that destructor out. the compiler will make it for you
pm100
And the compiler will generate that for you if you don't supply it.
Torlack
+2  A: 

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.

UncleBens
+3  A: 

No, you should not delete the std::string objects. they will be automatically freed up when their destructor's gets called.

SysAdmin