具有返回值 char* 返回垃圾的函数

Function with return value char* returning garbage

本文关键字:函数 返回 返回值 char      更新时间:2023-10-16

我正在尝试构建一个可以重用的实用程序类,用于转换std::string to a char*

char* Foo::stringConvert(std::string str){
      std::string newstr = str;
      // Convert std::string to char*
      boost::scoped_array<char> writable(new char[newstr.size() + 1]);
      std::copy(newstr.begin(), newstr.end(), writable.get());
      writable[newstr.size()] = ''; 
      // Get the char* from the modified std::string
      return writable.get();
}

当我尝试从 stringConvert 函数中加载输出时,代码有效,但是当在我的应用程序的其他部分使用时,此函数会返回垃圾。

例如:

Foo foo;
char* bar = foo.stringConvert(str);

上面的代码返回垃圾。对于此类问题,是否有任何解决方法?

我将假设writable是一个具有自动持续时间的对象,它会破坏它在析构函数中包含的char* - 这是你的问题 - 无论返回writable.get()什么都不再有效。

只需返回std::string,为什么需要原始char *

为什么不直接使用 std::string.c_str() ?这是一种库方法,可以满足您的需求。