c++ - 在类内的 union 内访问 map 会出现段错误

标签 c++ stl unions

我正在尝试创建一个包含一种类型或另一种类型的映射的类,因此我决定使用匿名 union 。但是当我尝试访问映射时,我的代码给出了一个段错误(在这种情况下,我在构造函数和析构函数中都遇到了一个段错误):

#include <map>
#include <string>
#include <iostream>

class Foo
{
    private:
        union
        {
            std::map<std::string, int> ints;
            std::map<std::string, std::string> strings;
        };

        bool fooContainsInts;

    public:

        Foo(bool containsInts) : fooContainsInts(containsInts) 
        {
            if (containsInts) {ints = std::map<std::string, int>();}
            else {strings = std::map<std::string, std::string>();}
        }

        ~Foo()
        {
            if (fooContainsInts) {ints.clear();}
            else {strings.clear();}
        }
};  

int main() 
{
    std::cout << "No segfault here!" << std::endl;
    Foo foo(true);
    std::cout << "This line doesn't get printed" << std::endl;
    return 0;
}

最佳答案

我会建议模板化类型而不是 union ,但也许这对你有帮助。

http://en.cppreference.com/w/cpp/language/union

第二个例子告诉你如何处理非 POD union 成员。

应该是这样的

    Foo(bool containsInts) : fooContainsInts(containsInts) 
    {
        if (containsInts) { new (&ints) std::map<std::string, int>;}
        else { new (&strings) std::map<std::string, std::string>;}
    }

    ~Foo()
    {
        if (fooContainsInts) { ints.~map<std::string, int>(); }
        else { strings.~map<std::string, std::string>(); }
    }

虽然现在我无法在 MSCV 上测试它。

您需要显式构造和析构非 POD union 类型

关于c++ - 在类内的 union 内访问 map 会出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39146181/

相关文章:

c++ - [ '(' token 之前的预期标识符或 '{' 错误]

c++ - C++ 中的一元运算符重载类型(新手)

c++ - 如何访问对象的私有(private)成员?

c++ - 在 std::map 中使用 std::auto_ptr 安全吗?

c - 用 char 数组成员填充 union

c - 为什么我的 union 没有显示正确的值?

struct - Rust:使用两个u8结构字段作为u16

c++ - Windows 应用程序的堆大小

c++ - 在 std::map 中查找不存在的键

c++ - 为什么 set<string>::iterator 不能作为 map 的 key?