Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I delete the string members of a C++ class?

Tags:

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?

like image 867
Blade3 Avatar asked Mar 02 '10 18:03

Blade3


People also ask

Do you have to delete Std string?

You can treat std::string like any other class. Use new for allocation, and delete once you're done with it. With C++11, I do not recommend usage of new and delete in most cases.

Do I need to delete strings C++?

Your string is a data member, so its destructor is called. Its destructor does everything that needs to be done here, so there is no more need (and in fact it would be very wrong) to clean anything up here than if you had the string as a local variable in main().

How do you call a destructor in C++?

A destructor is a member function that is invoked automatically when the object goes out of scope or is explicitly destroyed by a call to delete . A destructor has the same name as the class, preceded by a tilde ( ~ ). For example, the destructor for class String is declared: ~String() .


2 Answers

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()
{
}
like image 50
Liz Albin Avatar answered Oct 12 '22 20:10

Liz Albin


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.

like image 22
Gregor Brandt Avatar answered Oct 12 '22 21:10

Gregor Brandt