c++ - 枚举的 std::unordered_set,调用 find 给出段错误

标签 c++ c++11

#include <iostream>
#include <unordered_set>
#include <memory>

enum Config
{
    NO_NEW_LINE,
    TO_FILE,
    NO_CONSOLE
};

int main()
{
    std::shared_ptr<std::unordered_set<Config>> configurations;
    configurations->emplace(Config::NO_NEW_LINE);
    if (configurations->find(Config::NO_NEW_LINE) == configurations->end())
        std::cout << "nothing found " << std::endl;

    return 0;
}

我不知道为什么这段代码会出现段错误。

这是 gdb(在命名空间 SLog 中)

0x00005555555b2a1a in std::_Hashtable<SLog::Config, SLog::Config, std::allocator<SLog::Config>, std::__detail::_Identity, std::equal_to<SLog::Config>, std::hash<SLog::Config>, std::__detail::_Mod_range_hashing, std::__detail::_Default_ranged_hash, std::__detail::_Prime_rehash_policy, std::__detail::_Hashtable_traits<false, true, true> >::_M_bucket_index (this=0x0, __k=@0x7fffffffdbb4: SLog::NO_NEW_LINE, __c=0) at /usr/include/c++/7/bits/hashtable.h:631
631       { return __hash_code_base::_M_bucket_index(__k, __c, _M_bucket_count); }

最佳答案

你的 shared_ptr 不管理任何东西。 它相当于:

std::unordered_set<Config>* configurations;

在旧世界。

您可以通过以下方式轻松修复它:

configurations.reset(new std::unordered_set<Config>);

或者按照@user4581301 的建议:

auto configurations = std::make_shared<std::unordered_set<Config>>();

关于c++ - 枚举的 std::unordered_set,调用 find 给出段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57651712/

相关文章:

c++ - 在遍历 map 和打印内容时获取向后输出

变量重新分配中的 C++11 内存释放

c++ - std::array operator[] 与 get<>

c++ - 如何在 STL 容器和成员函数调用中存储模板化对象

c++ - 如何复制初始值设定项列表?

c++ - SDL2_image渲染无法正常工作

c++ - 隐藏包含父库

c++ - 为RealBasic创建与C/C++库的绑定(bind)

C++如何使用动态库(.so文件)

C++11 gcc : explicit qualification in declaration? 标准引用?