为什么我的作业操作员给出了损坏错误
Why is my assignment operator giving out a corruption error
我正在尝试为练习创建一个简单的共享指针。似乎我在任务操作员及其崩溃时有一个问题。我正在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被泄漏,新指针将获得额外的参考,而无需增加计数器。
相关文章:
- 在C++中检测到堆损坏错误
- AMQP-CPP:TCP 处理程序中的管道损坏错误
- 与强制转换相关的堆损坏错误
- 如何修复C ++中的"堆已损坏"错误?
- 双重释放或损坏错误(找不到错误?
- 对于我的类函数,我得到双重释放或损坏错误
- 为什么我的作业操作员给出了损坏错误
- 为什么 delete[] 会导致堆损坏错误
- 为什么我的visual c++在堆栈损坏的情况下没有触发堆栈损坏错误
- c++运行程序时出现堆已损坏错误
- 范围末尾的C 双免费或损坏错误
- Vector访问中出现内存损坏错误
- C 双免费或损坏错误
- 包含链接列表的链接列表给出了堆的损坏错误:原因
- 在Windows上立即检测到堆损坏错误.如何
- 双重释放或损坏错误
- 使用删除 [] 和新(放置)运算符的可视C++堆损坏错误
- 调试 MS VC++ 2005 中的堆损坏错误
- 堆损坏错误;无法发布 cv::Mat opencv
- 使用auto_ptr时出现内存损坏错误