字符串构造函数将两个字符* 放入另一个 std::string 在 C++14 中有效,但不适用于 C++17
string constructor taking two char* into another std::string works in c++14 but not c++17
以下程序尝试使用第一个字符串和指向第一个字符串中间的指针构造第二个字符串:
#include <string>
int main() {
std::string src = "hello world";
const char* end = &src[5];
std::string dest(src.data(), end);
}
在 C++14 及更早版本中,这有效。但在 C++17 中,调用失败:
error: no matching function for call to ‘std::__cxx11::basic_string<char>::basic_string(char*, const char*&)’
std::string dest(src.data(), end);
[... full output omitted ...]
是什么改变了导致这失败?
dest
的构造试图使用以下构造函数(来自 cpp首选项(:
template< class InputIt >
basic_string( InputIt first, InputIt last,
const Allocator& alloc = Allocator() );
这要求first
和last
具有完全相同的类型。问题是在 C++17 中,当在非常量std::string
上调用时,std::string::data
会返回一个非常量指针。这意味着first
的类型char*
,last
的类型const char*
。由于它们不同,因此无法推断模板参数InputIt
,并且调用失败。
无法将模板参数显式指定为构造函数调用,但有一个解决方案。 std::string::c_str
仍然返回一个const char*
,dest
的构造可以使用它:
std::string dest(src.c_str(), end);
另一种解决方案是通过 const 引用在str
上调用data()
:
const auto& const_src = src;
std::string dest(const_src.data(), end);
或者,如果您不关心C++14兼容性,则可以使用std::as_const
(感谢Mário Feroldi(
std::string dest(std::as_const(src).data(), end);
相关文章:
- 枚举环境变量的惯用C++14/C++17方法
- cppcheck在const std::string[]上引发警告
- 将std::string传递给WriteConsole API
- 为std::string的某个索引赋值
- std中有类似find_last_of的函数,而string中没有
- 使用 std::string () const 函数启动线程或未来
- 使用char类型将decimal转换为string,将string转换为decimal
- 迭代和比较映射<字符串、矢量<string>> c++ 中的值
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- 将向量解析<string>为字符串
- 'string.assign(string.data(), 5)' 是明确定义的还是 UB?
- 如何更改大小(std::string)
- "string.h"在构建适用于iOS的qt应用程序中找不到消息
- C++:如何将 unix 时间的字符串转换为 *tm?(使用时间错误:"cannot convert 'String' to 'tm*' ")
- std::string 的对象真的可以移动吗?
- 与'operator='不匹配(操作数类型'String'且"void")
- 错误的自动扣除 c++14
- 字符串构造函数将两个字符* 放入另一个 std::string 在 C++14 中有效,但不适用于 C++17
- C++14 中 std::string 的运算符后缀
- c++11/14 make_unique对std::string的异常重载