内存释放临时对象c ++

问题描述 投票:-1回答:1

我构建了一个简单的字符串类。我尝试制作串联功能,其中一个是+和另一个+=。当试图实现+=时,我生成一个Str对象,其下等于第一个字符串,其大小为s.size()。但是当我试图向它添加一个新的字符串t时,我需要释放旧的数组s字符串并为其分配新的大小。在调用temp Str对象的析构函数之后,它在释放旧空间时卡在那里,我无法理解为什么。如何在Str成员函数下解除分配+

class Str
{

public:
    typedef size_t size_type;
    typedef char* iterator;
    typedef const char* const_iterator;
    iterator begin(){ return p; }
    iterator end() { return p + std::strlen(p); }
    const_iterator begin() const { return p; }
    const_iterator end() const { return p + std::strlen(p); }

    size_type size() const { return data_length; }
    Str() {};


    Str(const Str& s): 
        p(new char[s.size() +1]), 
        data_length(s.size())
    {
        std::copy(s.begin(), s.end(), p);
        p[data_length] = '\0';
    }

    Str(const char* cp) :
        p(new char[std::strlen(cp) + 1 ]), 
        data_length(std::strlen(cp))
    {
        std::copy(cp, cp+ std::strlen(cp) + 1,p);//copies also the '\0' char to the last place in p
    }


Str& operator=(Str& rhs)//assignment operator
{
    if (&rhs != this)
    {
        uncreate();
        create(rhs.size());
        std::copy(rhs.begin(), rhs.end() + 1, p);
        //p[rhs.size()] = '\0';
    }
    return *this;
}

Str& operator=(const char* cp)//assignment operator
{
    if (cp!= p)
    {
        uncreate();
        create(std::strlen(cp));
        std::copy(cp, cp+std::strlen(cp), p);
        p[data_length] = '\0';
    }
    return *this;
}




    Str& operator+=(const Str&);

    ~Str() 
    {
        delete[] p;//stucked here while returning from + member function
        data_length = 0;
    }

    const char* c_str() const;
    void copy(char* ,size_type);
private:
    char* p;
    size_type data_length = 0;

    const_iterator ci() const { return p; }

    void uncreate();
    void create(size_type);
};



Str operator+(const Str& s, const Str& t)
{
    Str r = s;
    r += t;
    return r;   

}


inline Str& Str::operator+=(const Str &s)
{
    //trying to allocate new space for this object 

    std::copy(s.begin(),s.end(),p+this->size());
    p[data_length] = '\0';
    return *this;
}

void Str::create(Str::size_type n)
{
    p = new char[n + 1];
    data_length = n;
}

void Str::uncreate()
{
    delete[] p;//to check that p is allocated right
    data_length = 0;
}

main为例:

int main()
{

    Str s1 = "hello"; 
    Str s2 = "worly";
    Str s3 = s1 + s2;

    return 0;
}
c++ memory-management concatenation
1个回答
2
投票

我想你想要这样的东西:

inline Str& Str::operator+=(const Str &s)
{
    const int new_data_length = data_length + s.data_length;
    char * temp = new char[new_data_length + 1];
    memcpy(temp, p, data_length);
    memcpy(temp + data_length, s.p, s.data_length);

    delete [] p;
    p = temp;

    data_length = new_data_length;
    p[data_length] = 0;

    return *this;
}
© www.soinside.com 2019 - 2024. All rights reserved.