Double free or corruption after queue::push

前端 未结 6 982
礼貌的吻别
礼貌的吻别 2020-11-27 02:54
#include 
using namespace std;

class Test{
    int *myArray;

        public:
    Test(){
        myArray = new int[10];
    }

    ~Test(){
        de         


        
6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-27 03:41

    The problem is that your class contains a managed RAW pointer but does not implement the rule of three (five in C++11). As a result you are getting (expectedly) a double delete because of copying.

    If you are learning you should learn how to implement the rule of three (five). But that is not the correct solution to this problem. You should be using standard container objects rather than try to manage your own internal container. The exact container will depend on what you are trying to do but std::vector is a good default (and you can change afterwords if it is not opimal).

    #include 
    #include 
    
    class Test{
        std::vector myArray;
    
        public:
        Test(): myArray(10){
        }    
    };
    
    int main(){
        queue q
        Test t;
        q.push(t);
    }
    

    The reason you should use a standard container is the separation of concerns. Your class should be concerned with either business logic or resource management (not both). Assuming Test is some class you are using to maintain some state about your program then it is business logic and it should not be doing resource management. If on the other hand Test is supposed to manage an array then you probably need to learn more about what is available inside the standard library.

提交回复
热议问题