c++ - 如何获取 `std::basic_string<CustomClass>`进行编译?

标签 c++ string c++11 std stdstring

好的,我通常能够阅读、理解和修复编译器错误。但是对于这个,我想我需要帮助。

我想要一个std::basic_string<CustomClass>其中 CustomClass是一个类。我不想为它编写自定义 char_traits 和分配器类,除非绝对必要(即,如果可能,我想使用 std::char_traits<CustomClass>std::allocator<CustomClass>)。

如果我在 CustomClass 中没有构造函数,它编译得很好。一加就报错:

调用 'std::__1::basic_string<CustomClass, std::__1::char_traits<CustomClass>, std::__1::allocator<CustomClass> >::__rep' 的隐式删除默认构造函数

    #include <iostream>
    #include <string>
    //#include <vector>

    class CustomClass;

    typedef std::basic_string<CustomClass> InstanceString;
    typedef std::basic_string<int> IntString;

    class CustomClass
    {
    public:
        CustomClass()
            : m_X()
        {
        }

        CustomClass(const int x)
            : m_X(x)
        {
        }

    private:
        int     m_X;
    };

    int main(int argc, const char * argv[])
    {
        // This compiles fine
        IntString s1({1, 2, 5});

        // This would compile fine if there were no explicit constructors in Instance
        //InstanceString s2e = InstanceString({Instance(), Instance(), Instance()});

        // This generates errors
        InstanceString s2 = InstanceString({CustomClass(1), CustomClass(3), CustomClass(5)});

        std::cout << "Hello, World!\n";
        return 0;
    }

我知道这可能与隐式/显式构造函数、复制/移动语义等有关。

我的问题是:

  • 我如何让它编译(即我应该向类中添加什么构造函数/东西)
  • 我如何系统地弄清楚如何修复这些类型的编译错误?

最佳答案

从字符串库[strings.general]/1的描述的第一句开始:

This Clause describes components for manipulating sequences of any non-array POD type. In this Clause such types are called char-like types, and objects of char-like types are called char-like objects or simply characters.

CustomClass 不是 char-like 类型,因为它不是 POD 类型,因此它不能存储在 basic_string 中>.

libc++ 实现无法编译,因为它使用了短字符串优化,并且在这样做时假设有可能在 union 中包含一个 CharT 数组无需提供自定义构造函数。

关于c++ - 如何获取 `std::basic_string<CustomClass>`进行编译?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12290276/

相关文章:

c++ - 模板类型方法 GTesting

c++ - 在 opencv 中索引矩阵的最佳方法

c - 从函数返回 char* 和 char[] 有什么区别?

c++ - 部分模板-基于模板的特化与显式部分模板特化

c++ - C++11 默认构造函数中的引用初始化

c++ - 从 UMDF 驱动程序 (C++) 调用 CreateFile 时出现“访问被拒绝”错误

c++ - 在 Visual Studio 的哪个版本中引入了函数?

c - 如何从c中的文件中正确读取某些字符串?

javascript - 如何在 div 中设置第三个单词的样式并在新代码的一部分中使用该文本?

c++ - safe_ptr 实现