Karel Demeester Karel Demeester - 1 month ago 27
C++ Question

c++11 - initialize std::string from char* directly with {} constructor

I have a function which accepts a

std::string&
:

void f(std::string& s) { ... }


I have a
const char*
which should be the input parameter for that function. This works:

const char* s1 = "test";
std::string s2{s};
f(s2);


This doesn't:

const char* s1 = "test";
f({s1});


Why isn't this possible? The funny thing is that CLion IDE is not complaining, but the compiler is:

no known conversion for argument 1 from β€˜<brace-enclosed initializer list>’ to β€˜std::basic_string<char>&’

Answer

This has nothing to do with constructing std::string from char const*.

f expects a lvalue reference to a string, and by creating a temporary instance on the spot, you're providing an rvalue, which cannot be bound to a non-const lvalue reference. f(string{}) is just as invalid.