为什么在添加整数时,STD :: String返回字符串的尾巴

Why does std::string return the tail of the string when adding an integer

本文关键字:返回 String 字符串 STD 添加 整数 为什么      更新时间:2023-10-16

我知道您无法使用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的对象时,您会得到相同的东西位于终止空字符的位置。