Why implicit conversion from const char* to std::string does not work in the latter case?
Link a reference to C++ standard if possible, please.
Variant 1:
struct Foo {
Foo(const char* a) {}
};
int main() {
// works well for a "const char*" accepting constructor
Foo* foo = new Foo[1] { "a" };
}
Variant 2:
struct Foo {
Foo(std::string a) {}
};
int main() {
// could not convert from "const char*" to "Foo"
Foo* foo = new Foo[1] { "a" };
}
At most one user-defined conversion is allowed in a user-defined conversion sequence (12.3p4).
You can use an extra level of braces to make it work:
Foo* foo = new Foo[1] { {"a"} };
Note that because of a bug in clang it requires Foo to have a default constructor Foo::Foo() even though it will not actually be called.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With