为什么我的赋值运算符发出了损坏错误

时间:2018-02-16 01:14:35

标签: c++ c++11

我正在尝试为练习创建一个简单的共享指针。好像我在赋值运算符中有一个问题,当我这样做时它崩溃了。 我在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

1 个答案:

答案 0 :(得分:2)

您在分配时没有正确维护计数器。您的旧_mtype被泄露,新指针获得额外的引用而计数器不会增加。