double free detected in tcache 2 c++

Рейтинг: -2Ответов: 1Опубликовано: 18.08.2023
#include <iostream>

using namespace std;

template <typename T>

class SmartPointer {
    private:
        T* p;
        int count = 0;
    public:

        SmartPointer(T* pb) { // Конструктор
            p = pb;
            count++;
            cout << "Constructor - " << (&p) << count << endl;
        }

        SmartPointer(const SmartPointer& ConPtr) {
            p = ConPtr.p;
            count = ConPtr.count;
            count++;
            cout << "Constructor Copy - " << (&p) << count << endl;
        }

        SmartPointer& operator = (const SmartPointer& ConOper) {
            if (this != &ConOper) {
                Release();
                p = ConOper.p;
                count = ConOper.count;
                count++;
                cout << "Reload operator - " << (&p) << count << endl;
            }
            return *this; 
        }

        ~SmartPointer() { // Деструктор
            cout << "Destructor" << (*p) << endl;
            delete p;
            //cout << "Destructor"<< (*p) << endl;
        }

        void Release() { // Освобождение ресурсов
            delete p;
            p = nullptr;
        }

        void Print() {
            cout << (*p) << " count - " << count << endl;
        }
};

int main() {
    int* pm = new int(7);
    int* pn = new int(10);
    SmartPointer<int> A(pm);
    SmartPointer<int> B(A);
    SmartPointer<int> C(pn);
    C.Print();
    C = A;
    A.Print();
    B.Print();
    C.Print();
    return 0;
}

Добрый день, объясните пожалуйста ошибку - double free detected in tcache 2. Я понимаю что два объекта ссылаются на один участок памяти, но как этого избежать? Перепробовал кучу вариантов, ничего не получается.

Ответы

▲ 0Принят

Смарт поинтер должен хранит указатели лично и при передачи указателя другому экземпляру должен у себя отказаться от контроля. примерно так : p = nullptr ; count = 0 ;
Вот пример рабочий такой:

#include <iostream>

using namespace std;

template <typename T>

class SmartPointer {
    private:
        T* p;
        int count = 0;
    public:

        SmartPointer( T * & pb ) { // Конструктор !!!
            p = pb;
            pb = nullptr ; // !!!
            count++;
            cout << "Constructor - " << (&p) << count << endl;
        }

        SmartPointer(SmartPointer & ConPtr) { // !!!
            p = ConPtr.p;
            ConPtr . p = nullptr ; // !!!
            count = ConPtr.count;
            ConPtr.count=0;
            cout << "Constructor Copy - " << (&p) << count << endl;
        }

        SmartPointer& operator = ( SmartPointer & ConOper) { // !!!
            if (this != &ConOper) {
                Release();
                p = ConOper.p;
                ConOper . p = nullptr ; // !!!
                count = ConOper.count;
                ConOper.count=0;
                cout << "Reload operator - " << (&p) << count << endl;
            }
            return *this; 
        }

        ~SmartPointer() { // Деструктор
          if ( p ) // !!!
            cout << "Destructor" << (*p) << endl;
          else
            cout << "Destructor Null" << endl;  
          delete p;
          //cout << "Destructor"<< (*p) << endl;
        }

        void Release() { // Освобождение ресурсов
            delete p;
            p = nullptr;
        }

        void Print() {
          if ( p ) // !!!
            cout << (*p) << " count - " << count << endl;
          else  
            cout << "Null count - " << count << endl;
        }
};

int main() {
    int* pm = new int(7);
    int* pn = new int(10);
    SmartPointer<int> A(pm);
    SmartPointer<int> B(A);
    SmartPointer<int> C(pn);
    C.Print();
    C = A;
    A.Print();
    B.Print();
    C.Print();
    return 0;
}