Karel Demeester Karel Demeester - 6 months ago 73
C++ Question

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

I have a function which accepts a


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};

This doesn't:

const char* s1 = "test";

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>&’


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.