我使用C++ 11用gcc 4.8.5和在我的代碼差錯部分是這樣的:段錯誤與共享指針
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_)
會導致段錯誤,所以如何解決它?只有
是一個有效的指針? –
它似乎很有可能'task_items [i]'是'nullptr'(或空的共享指針) –
你介意嘗試'if(item){items.push_back(item)}'嗎? –