具有返回值 char* 返回垃圾的函数
Function with return value char* returning garbage
我正在尝试构建一个可以重用的实用程序类,用于转换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()
?这是一种库方法,可以满足您的需求。
相关文章:
- 从函数返回const char*数组
- 检查函数返回类型是否与STL容器类型值相同
- 从 c 或 cpp 系列子函数返回到主函数
- 从函数返回任意简单类型的数据
- 警告:在函数返回类型 [-Wignore 限定符] 时忽略类型限定符
- 从 C++ 中的函数返回数组地址问题
- VirtDisk.h QueryChangesVirtualDisk() 函数返回 RangeCount 为 0
- 为什么glGetSubroutineIndex为不同的函数返回相同的值?
- 在 c++ 中将函数返回类型指定为模板参数
- 从封装在对象中的函数 C++ 返回时为空的列表
- 为什么向量内部的指针在从函数返回时会发生变化?
- 函数返回的 rvalue 引用(表达式)是 xvalue - 但没有标识?
- 程序中的布尔函数返回输入的范围无论如何都是无效的
- 寿命延长从函数返回引用
- 程序不向函数返回值
- 字符串函数返回奇怪的值
- 类的大问题,以及从空函数c++返回
- 为什么在尝试测量函数返回所需的时间时,我的运行时编号是错误的?
- C++二叉搜索树模板从函数返回节点
- NVCC 错误:string_view.h:constexpr 函数返回是非常量