我有以下代码:
#include <memory>
#include <vector>
#include <iostream>
class MarchingEvent
{
public:
MarchingEvent() {}
};
class DerivedEvent : public MarchingEvent
{
public:
DerivedEvent() {}
};
std::shared_ptr<MarchingEvent> function1()
{
return std::make_shared<DerivedEvent>();
}
std::shared_ptr<MarchingEvent> function2()
{
std::shared_ptr<MarchingEvent> event = function1();
if (event)
return event; // This line crashes...
return std::shared_ptr<MarchingEvent>();
}
int main()
{
std::shared_ptr<MarchingEvent> event = function2();
std::cout << "hello";
return 0;
}
运行 function2()时,在行 return event上发生崩溃; ,该崩溃是SIGABRT,可以追溯到标准文件 shared_ptr_base。 h :
// Counted ptr with no deleter or allocator support
template<typename _Ptr, _Lock_policy _Lp>
class _Sp_counted_ptr final : public _Sp_counted_base<_Lp>
{
public:
explicit
_Sp_counted_ptr(_Ptr __p)
: _M_ptr(__p) { }
virtual void
_M_dispose() noexcept
{ delete _M_ptr; }
您是否知道我在做什么错?
答案 0 :(得分:0)
创建一个简单的MCVE。它将证明:
a)您的实现存在错误(极不可能),或者
b)您在其他地方(非常可能)有错误或UB
MCVE示例:
#include <memory>
#include <vector>
#include <iostream>
class MarchingEvent
{
};
class DerivedEvent : public MarchingEvent
{
};
std::shared_ptr<MarchingEvent> function1()
{
return std::make_shared<DerivedEvent>();
}
std::shared_ptr<MarchingEvent> function2()
{
std::shared_ptr<MarchingEvent> event = function1();
if (event)
return event; // This line crashes...
return std::shared_ptr<MarchingEvent>();
}
int main()
{
for (int i = 0 ; i < 10 ; ++i)
{
std::vector<std::shared_ptr<MarchingEvent>> v(10000);
for(int j = 0 ; j < 10000 ; ++j)
{
v[j] = function2();
}
}
std::cout << "done\n";
}
我的主张有力的证据:http://coliru.stacked-crooked.com/a/1b554b334212a0ea