C++ 为什么我的赋值运算符出现损坏错误

C++ 为什么我的赋值运算符出现损坏错误,c++,c++11,C++,C++11,我正在尝试创建一个简单的共享指针以供练习。好像我在赋值操作符中遇到了问题,当我这样做时它崩溃了。 我正在计算机上运行此代码 这是我的密码 struct foo { foo() { } int a; }; template <typename t> class shared { public: shared() { _mtype = new t(); counter = counter +1;

我正在尝试创建一个简单的共享指针以供练习。好像我在赋值操作符中遇到了问题,当我这样做时它崩溃了。 我正在计算机上运行此代码

这是我的密码

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";
}

作业中没有正确维护计数器。您的旧_mtype被泄漏,新指针得到一个额外的引用,而计数器没有增加。

“我有一个问题”“它崩溃了”这不是一个可接受的问题陈述。呈现一个带有清晰注释的输出。好的,让我编辑我的问题权限授予好的,所以它是双重自由。现在通过调试器运行程序,在每个步骤中观察每个对象中的
计数器的值。此时,您会发现,
计数器
实际上并没有做任何事情(在复制构造的情况下,除了下溢),计数器需要在对象之间共享。通常,它存储在管理的同一内存中,您应该保留一个指向
struct{int counter;T data}。多个对象可以指向它,并递增/递减同一个计数器。尽管正确,但修复此问题所需的时间远远超过在
操作符=
定义中递增
计数器所需的时间。除非我遗漏了什么,否则这个设计是有缺陷的修复了problem@MistyD:不,没有。@LightnessRacesinOrbit是否有任何关于此设计可能存在缺陷的建议?我只是在练习,很想听suggestions@MistyD:现在此引用的
计数器
等于2,但当另一个对象超出范围时,它仍将取消分配内存,使此引用无效。如果你也增加另一个计数器,那么你就会有内存泄漏。您就是不能这样做,因为您需要单独的
计数器
。不同的参考资料需要以某种方式相互了解。
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