为什么我的作业操作员给出了损坏错误

Why is my assignment operator giving out a corruption error

本文关键字:损坏 错误 我的 作业 操作员 为什么      更新时间:2023-10-16

我正在尝试为练习创建一个简单的共享指针。似乎我在任务操作员及其崩溃时有一个问题。我正在Coliru

上运行此代码
_mtype = obj._mtype;

这是我的代码

struct foo
{
    foo()
    {
    }
    int a;
};
template <typename t>
class shared
{
    public:
    shared() 
    {
        _mtype = new t();
        counter = counter +1;
    }
    t* operator->()
    {
        return _mtype;
    }
    void operator=(const shared<t>& obj)
    {
        std::cout << "Assignment operator" <<std::endl;
        this->_mtype = obj._mtype; //Crashing here ? Why is this happening ?
        //return _mtype;
    }
    ~shared()
    {
        counter = counter -1;
        if(counter == 0)
             delete _mtype;
    }
    public:
    int counter = 0;
    t* _mtype = nullptr;
};
int main()
{
    shared<foo> f;
    f->a = 12;
    shared<foo> g;
    g = f;   ///-------Issue starts here
    std::cout << "Finished";
}

这是我得到的输出

Assignment operator
*** Error in `./a.out': double free or corruption (fasttop): 0x0000000001acdc20 ***
======= Backtrace: =========
/lib/x86_64-linux-gnu/libc.so.6(+0x777e5)[0x7f950cf097e5]
/lib/x86_64-linux-gnu/libc.so.6(+0x7fe0a)[0x7f950cf11e0a]
/lib/x86_64-linux-gnu/libc.so.6(cfree+0x4c)[0x7f950cf1598c]
./a.out[0x40097b]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf0)[0x7f950ceb2830]
./a.out[0x400a19]
======= Memory map: ========
Finishedbash: line 7: 32173 Aborted                 (core dumped) ./a.out

您无法正确维护分配中的计数器。您的旧_mtype被泄漏,新指针将获得额外的参考,而无需增加计数器。