带有共享指针的段错误

时间:2017-09-18 03:57:20

标签: c++ c++11

我使用的是带有gcc 4.8.5的c ++ 11,我的代码中的错误部分是这样的:

vector<shared_ptr<My_Type>> items;
for(int i = 0; i < num_dequeued; i++) {
    auto & item = task_items[i];
    items.push_back(item->my_type_); //here item->my_type_ is declared as 'shared_ptr<My_Type>', and this is the error line
}

和gdb显示:

Program received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0x7fffc6ffd700 (LWP 9632)]
0x000000000043254c in __shared_ptr (this=0x7fffb19ed7d0) at /usr/include/c++/4.8.2/bits/shared_ptr_base.h:779
779       __shared_ptr(const __shared_ptr&) noexcept = default;

我不明白为什么items.push_back(item->my_type_)会导致段错误,所以如何解决?

1 个答案:

答案 0 :(得分:1)

仅有两种可能性:

  1. 你的指针是nullptr。 (item->my_type_
  2. num_dequed正在超越索引? (items[i]访问该元素,但尚未崩溃,之后崩溃)
  3. 我认为这些是在您的代码中查找(本地)的唯一可能性。否则我很确定问题出在其他地方。