c++11-使用{}构造函数直接从char*初始化std::string

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

本文关键字:char 初始化 std string 使用 构造函数 c++11-      更新时间:2023-10-16

我有一个接受std::string&:的函数

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

我有一个const char*,它应该是该函数的输入参数。这项工作:

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

这不是:

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

为什么这不可能?有趣的是,CLion IDE并没有抱怨,但编译器是:

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

这与从char const*构造std::string无关。

f需要一个字符串的左值,通过当场创建一个临时实例,您提供了一个右值,该右值不能绑定到非常量左值引用。f(string{})同样无效。

您的函数接收到一个非常量引用,并且您正在传递一个临时对象,该对象需要一个副本或常量引用参数。两种解决方案,创建另一个函数以接收对象作为右值引用,并调用中的另一个重载

void f(string&& s) {  f(s); } 

允许将临时对象作为参数,或更改函数定义以接收任何对象,但作为常量引用

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

一个选项是更改函数,使其按值而不是按引用获取字符串。然后它就会起作用。在任何情况下,在C++11中,有时最好通过值传递,而不是通过引用传递。