首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >枚举的std::unordered_set,调用find时出现分段错误

枚举的std::unordered_set,调用find时出现分段错误
EN

Stack Overflow用户
提问于 2019-08-26 12:21:19
回答 1查看 166关注 0票数 1
代码语言:javascript
复制
#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中)

代码语言:javascript
复制
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); }
EN

回答 1

Stack Overflow用户

发布于 2019-08-26 13:32:33

您的shared_ ptr不管理任何内容。相当于:

代码语言:javascript
复制
std::unordered_set<Config>* configurations;

在旧世界。

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

代码语言:javascript
复制
configurations.reset(new std::unordered_set<Config>);

或者像@user4581301建议的那样:

代码语言:javascript
复制
auto configurations = std::make_shared<std::unordered_set<Config>>();
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57651712

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档