【问题标题】:Adding a pointer to a string in C++在 C++ 中添加指向字符串的指针
【发布时间】: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&amp;, const char*)
  • 为什么你认为s += s2; 不应该工作?不应该工作的是return s.c_str();,因为它返回一个指向当调用者获取它时不再存在的对象的指针。

标签: c++ pointers constants


【解决方案1】:

变量sappend 函数中是局部变量。一旦append 函数返回,该变量就会被破坏,留下一个指向不再存在的字符串的指针。使用这个指针指向undefined behavior

关于如何解决这个问题的提示:一直使用std::string

【讨论】:

    【解决方案2】:

    您正在将const char* 指针添加到std::string,这是可能的(请参阅this reference)。不可能对 char* 类型(C 样式字符串)进行该操作。

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

    【讨论】:

      【解决方案3】:

      类 std::string 为 const char * 类型的操作数重载了 operator +=

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

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

      char s[12] = "Hello ";
      const char *s2 = "World";
      
      std::strcat( s, s2 );
      

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

      printf("%s", total);
      

      可能导致未定义的行为。

      【讨论】:

        猜你喜欢
        • 2011-04-12
        • 1970-01-01
        • 2021-06-28
        • 1970-01-01
        • 2013-02-16
        • 2015-05-19
        • 1970-01-01
        • 2021-12-23
        • 1970-01-01
        相关资源
        最近更新 更多