【发布时间】:2014-07-30 18:50:56
【问题描述】:
我对 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;
}
【问题讨论】:
-
stdio.h在 C++ 中已弃用。使用cstdio。不管怎样,你有undefined behaviour。 -
您实际上是在返回指向局部变量的指针/引用,这是未定义的行为
-
您正在返回一个指向局部变量的指针(未定义的行为)。
-
它使用运算符函数
operator+(std::string&, const char*)。 -
为什么你认为
s += s2;不应该工作?不应该工作的是return s.c_str();,因为它返回一个指向当调用者获取它时不再存在的对象的指针。