关于c ++中的析构函数;

mef*_*mef 2 c++ destructor

我写了一个名为octed_string的类,没有析构函数,它运行良好但是它无法在函数中返回任何octed_string类型.

请看下面的代码并告诉我有什么问题.

当我删除析构函数它工作!(cout print 12)

任何人都可以帮忙吗?

class octed_string
{
private:
    uint8_t *value;
    size_t length;
    size_t allocated;
public:
    octed_string()//constructor
        :value(0),length(0),allocated(0)
    {

    }
    void copy(uint8_t *from, uint8_t *to)
    {
        for (size_t i = 0; i < length; i++)
            *to++ = *from++;
    }

    void allocate()
        {
            if (value == 0)
            {
                allocated = STACK_INITIAL_ALLOC;
                value = new uint8_t[allocated];
            }
            else
            {
                // We need to allocate more memory

                size_t new_allocated = allocated + STACK_CHUNK_ALLOC;
                uint8_t *new_value = new uint8_t[new_allocated];

                // Copy from old stack to new stack
                copy(value, new_value);

                // Delete the old value
                delete [] value;

                allocated = new_allocated;
                value = new_value;
            }
        }

    ~octed_string()//destructor
    {
        if(value)
            delete [] value;
    }

    friend ostream &operator<<(ostream &_output,const octed_string &_str)//opration overloading for cout
    {
        for(int i=0;i<_str.length;i++)
            _output<<(uchar_t)_str.value[i];
        return _output;
    }

    void add(uint8_t input)//this function automatically add space to value (new)
    {
        if (length == allocated)
            allocate();  // Allocate more memory

        value[length++] = _value;
    }

    octed_string sub_string(int start,int end)//( this function has a problem with destructor i think because it return octed_string)
    {
        octed_string a;
        for(int i=start;i<end;i++)
            a.add(a);
        return a;
    }
};

void main()
{
    octed_string o; //object
    o.add(1);
    o.add(2);
    o.add(3);

    cout<<o.sub_string(0,2); //i expect printing 12 but i does not!
}
Run Code Online (Sandbox Code Playgroud)

----------------------- //通过添加以下代码修复phresnel修复:

octed_string(const octed_string &_input)
    :value(0),length(0),allocated(0)
{
    while(length<_input.length)
    {
        this->add((uchar_t)_input[length]);
    }
}

octed_string& octed_string::operator= (octed_string const& _in)
{
    octed_string tmp(_in);
    return *this;
}
Run Code Online (Sandbox Code Playgroud)

但我仍然无法理解原因.任何机构都可以提供任何参考来学习这个问题吗?

hmj*_*mjd 11

您需要为其定义复制构造函数和赋值运算符octed_string.

当你没有析构函数时,它可以正常工作,因为为成员变量分配的内存value不会被销毁,而默认复制构造函数构造的副本会引用原始(现在已销毁)对象所执行的相同的未删除内存.

当你有一个析构函数时,内存将被删除.

sub_string()返回时创建副本.