我尝试运行这段代码:
//find() should return a std::optional<std::reference_wrapper<std::shared_ptr<pieces>>>
//pieces is an abstract class
const auto find_result = array_of_shared_ptr_wrapper.find(target) ;
//ensure find_result has value...
const auto& piece_at_target = find_result.value().get();
std::cout << piece_at_target.use_count() << std::endl;
//Print 2 as expected, using a debugger the pointer still point to the
//same address as the pointer in the array, the data inside is still correct.
std::cout << piece_at_target.use_count() << std::endl;
//Print random garbage, piece_at_target underlying pointer is changed, now different
//from the one in the array, the data inside is messed up.
所以我的问题是这怎么会发生?任何避免此问题的方法,因为我试图将
piece_at_target
设置为 nullptr
并且出现分段错误。在使用调试器进行调查后,代码似乎试图删除指向随机垃圾的指针,这导致了错误。