我对 C++ 中的 const 指针感到困惑,并编写了一个小应用程序来查看输出是什么。我正在尝试(我相信)添加一个指向字符串的指针,这应该无法正常工作,但是当我运行程序时,我正确地得到“hello world”。谁能帮我弄清楚这条线 (s += s2) 是如何工作的?

我的代码:

#include <iostream>
#include <stdio.h>
#include <string>

using namespace std;

const char* append(const char* s1, const char* s2){
    std::string s(s1);     //this will copy the characters in s1
    s += s2;               //add s and s2, store the result in s (shouldn't work?)
    return s.c_str();      //return result to be printed
}

int main() {
    const char* total = append("hello", "world");
    printf("%s", total);
    return 0;
}
有帮助吗?

解决方案

变量sappend函数内的本地。一旦append函数返回该变量被拆除,将向您带到不再存在的字符串。使用此指针导致 未定义行为

我的提示你如何解决这个问题:使用 std::string 所有方式!

其他提示

你正在添加 const char* 指向一个的指针 std::string 这是可能的(参见 这个参考)。不可能进行该操作 char* 类型(C 风格字符串)。

但是,您返回的是指向局部变量的指针,因此一旦函数 append 返回并从堆栈中弹出,返回的指针指向的字符串将不存在。这会导致未定义的行为。

类 std::string 已重载 operator += 对于类型的操作数 const char *

basic_string& operator+=(const charT* s);

事实上,它只是将这个指针指向的字符串附加到 std::string 类型的对象的内容中,如果需要的话还会额外分配内存。例如,在内部重载运算符可以使用标准 C 函数 strcat从概念上讲,它类似于以下代码片段。

char s[12] = "Hello ";
const char *s2 = "World";

std::strcat( s, s2 );

考虑到您的程序具有未定义的行为,因为 total 退出函数append后销毁本地对象后将无效。所以 main 中的下一条语句

printf("%s", total);

可能会导致未定义的行为。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top