Ok, I’m usually all right at being able to read, understand and fix compiler errors. But with this one, I think I need help.
I want to have a std::basic_string<CustomClass> where CustomClass is a class. I don’t want to write custom char_traits and allocator classes for it, unless absolutely necessary (i.e. I want to use std::char_traits<CustomClass> and std::allocator<CustomClass> if possible).
It compiles fine if I have no constructors in CustomClass. As soon as I add one, there are errors:
Call to implicitly-deleted default constructor of '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;
}
I understand this probably has to do with implicit/explicit constructors, copy/move semantics and stuff like that.
My question is:
- how do I get it to compile (i.e. what constructors/something should I add to the class)
- and how do I systematically figure out how to fix these types of compilation errors?
As you said, the error message says
I’m pretty sure that
__rephere is yourCustomClass. It’s saying it’s trying to call the default constructor, but that’s been implicitly deleted (by you providing your own constructor). I’m guessing thatbasic_stringusesstd::is_default_constructible<>. As such, you need to provide a default constructor usingas Mooing Duck suggested in the comments.
It seems likely that it actually uses
std::is_trivially_default_constructible<>, which imposes the restriction that your class must be trivially constructible as well.