gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 15:06:51 25 4
gpt4 key购买 nike

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

我想要一个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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com