为什么在添加整数时,STD :: String返回字符串的尾巴
Why does std::string return the tail of the string when adding an integer
我知道您无法使用operator+
将整数连接到std::string
,而无需将其转换为char*
或std::string
。
但是为什么添加整数会返回字符串的尾巴?
#include <iostream>
#include <string>
int main()
{
std::string x;
x = "hello world" + 3;
std::cout << x << std::endl;
}
打印:lo world
如果您更改:x = "hello world" + 8;
我们打印:rld
这背后的原因是什么?未定义的行为?
您需要知道您的类型。FIR,您是不是将3添加到std::string
。加法发生在创建std::string
之前。取而代之的是,您将3添加到char[12]
,这是定义的,因为char数组衰减到char*
,并将3添加到IT上,将指针通过3个元素推高。这正是您所看到的。
比std::string
是由结果构建的,您最终会得到 tail 。
它等效于:
#include <iostream>
#include <string>
int main()
{
std::string x;
const char* p = "hello world";
p = p + 3;
x = p;
std::cout << x << std::endl;
}
您可以这样更安全:
#include <iostream>
#include <string>
using namespace std::literals;
int main()
{
std::string x;
x = "hello world"s + 3; // error! won't compile
std::cout << x << std::endl;
}
,因为您知道字符串是一个字符阵列,如果将+ 3
放置在CC_13,则说明您将将字符串从第三位置带到其末端
int data[5] = { 1, 2, 3, 4, 5 };
int *dp = data;
std::cout << *(dp + 3) << 'n';
现在,在这里,dp + 3
点在数据阵列中的4点;那只是指针算术。因此 *(DP 3)是4,这就是您在输出流中看到的。
char*
的同一件事:向其添加整数可为您提供一个新的指针值,从原始值偏移了整数的值:
char data[5] = "abcd";
char *dp = data;
std::cout << *(dp + 3) << 'n';
dp
点在数组的开头,而dp + 3
点点为" D"。因此 *(DP 3)是D,这就是您在输出中看到的。
当您使用指针和偏移量来初始化类型std::string
的对象时,您会得到相同的东西位于终止空字符的位置。
相关文章:
- 如何使用 uint64_t 键类型从 std::map<int, std::string> 返回值?
- 像 std::list<std::p air<string, string>> 这样的结构在返回时会被复制吗?
- 在先前调用 string::find 后添加内存分配和内存集会导致它返回 npos.为什么?
- std::hash<std::string> 可以为不同的字符串返回相同的值吗?
- 错误:为"运算符 std::string {aka std::__cxx11::basic_string}"指定的返回类型<char>
- 返回std::string的函数返回零
- Arduino trim() 和 replace() 方法返回从 'void' 到非标量类型'String'请求的转换
- 从内部使用静态 std::string 的函数返回 const char * 是否安全?
- std::string 的 c_str() 函数如何返回以 null 结尾的字符串?
- 从类方法返回 "const char*" 作为 std::string&
- std::string::find 为取消引用的迭代器和等效字符串文本返回不同的值
- 检查 std::string.c_str() 的返回值
- std::string::c_str() 曾经返回 nullptr 吗?
- std::logic_error 尝试返回 std::string 时
- std::string::find 总是返回 string::npos 偶数
- C 11 STD :: Promise返回STD :: String从线程中返回String,数据指针看起来已复制
- 为什么从 const 方法返回 string&无法编译?
- 通过JNI将我的Java API扩展到c++:如何包装返回String的方法
- 在main方法中调用返回String的函数
- 函数返回string.c_str()作为atoi()异常行为的参数