double free or corruption (runs ok if reorder lines)

This question already has an answer here:

  • Double free or corruption…but why? 6 answers
  • What is The Rule of Three? 8 answers

  • Your type manages resources (a dynamically allocated array) but does not implement the rule of three. When you do this:

    q.push_back(t);
    

    q makes a copy of t , which it owns. So now you have two copies of an object referring to the same data, and attempting to call delete in it.

    You need to implement a copy constructor and an assignment operator. Or use a class that manages its own resources, such as std::string or std::vector .

    Calling delete[] on an already deleted array is undefined behaviour (UB). This means that sometimes your program might seem to work. You cannot rely on a program with undefined behaviour to do anything. Swapping lines 1 and 2 inverts the order in which t and q get destroyed. This seems to yield a different result on your platform, but both are UB.


    C++ automatically makes a shallow copy of your Test object when you push it to the vector. When the vector goes out of scope and is destructed, the myArray pointer is delete[] d. Then, when Test goes out of scope, the same pointer is delete[] d again.

    You should specify a copy constructor and make a deep copy of the object. Along with a new array.

    Overloading assignment operator (explained in the same link as above) is also strongly suggested.


    Because you need a copy constructor.

    push_back copies the argument and as you haven't provided a copy constructor, there's a default one, making a shallow copy (copy just the pointer, without the content *)

    So, you need to define a

    Test( const Test& other )
    {
        // ...
    }
    Test& operator=( const Test& other ) // just in case
    {
        // ...
    }
    

    and make a deep copy, manually copying the char* buffer.

    *) which leads to double deletion - once from the t 's destructor, once from the q 's destructor (which calls the destructors of all elements in the vector)

    链接地址: http://www.djcxy.com/p/73182.html

    上一篇: 在C ++中复制构造函数

    下一篇: 双重免费或腐败(如果重新排序,则运行正常)