关于 shared_ptr 的问题

Questions about shared_ptr

我已经在 C++ Primer 中编写了练习 12.28,但我卡在了 shared_ptr 中。代码可以编译,但是执行的时候会崩溃。我以为我误用了 shared_ptr。请帮我检查以下代码:

map<string, shared_ptr<set<size_t>>> word_line;
//some performances to deal with word_line, everything goes normally
string word;
cin >> word;
map<string, shared_ptr<set<size_t>>>::iterator find_word = word_line.find(word);
//the programm crashes when the following codes execute
int line_size = (*(find_word->second)).size();

您忘记检查该词是否存在于地图中。如果密钥不存在,则 find returns word_line.end() 在这种情况下 find_word->second 具有未定义的行为。

即使找到了这个词,你也忘了检查共享指针是否指向null。如果它确实指向 null,则 *(find_word->second) 具有未定义的行为。