c++11-使用{}构造函数直接从char*初始化std::string
c++11 - initialize std::string from char* directly with {} constructor
我有一个接受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中,有时最好通过值传递,而不是通过引用传递。
相关文章:
- 初始化或分配空字符串文字到指向 C 中的 char 的指针或指向 C++ 中 const char 的指针的原因是什么
- 使用指针初始化 char 数组或字符串 C++
- 需要帮助在 c++ 中将字符串转换为字符 ----错误 "const char *" 类型的值不能用于初始化 "char" 类型的实体
- 对象初始化后在C++中显示 char 数组时的异常行为
- c ++ 如何在构造函数中初始化 char
- 无法使用类型 'const char *' 的左值初始化类型 'char *' 的成员子对象
- 以这种方式初始化的 char 数组是否会自动添加空终止符?
- 为什么 char 可以在 std::array 中初始化为 nullptr,而不是单独初始化?
- 使用 const char* 初始化 const ref 字符串成员时幕后会发生什么
- 如何使用 C++ 中的原语初始化类(如 std::字符串从 const char* 初始化)
- C++ 如何检查 char 变量是否未定义(未初始化)
- 在这种情况下,如何从类型 "const char*" 初始化字段?
- 为什么通过添加字符串文字和char初始化时,为什么不打印字符串
- 从二维数组中的char*初始化c++字符串时,读取大小为1的无效值
- 使用 char 初始化多维数组
- c++中的char初始化构造函数
- 如何从vector char初始化stringstream
- c++11-使用{}构造函数直接从char*初始化std::string
- 用const char初始化2D char数组元素
- 如何从const unsigned char*初始化std::istringstream,无需强制转换或复制