Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit conversion in array initializer list

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" };
}
like image 251
Hertz Avatar asked Sep 16 '26 13:09

Hertz


1 Answers

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.

like image 89
ecatmur Avatar answered Sep 19 '26 01:09

ecatmur



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!