2012-06-25 44 views
0

我试图建立一个实用工具类,我可以重新使用,即转换一个std::string to a char*功能的返回值的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()] = '\0'; 
     // Get the char* from the modified std::string 
     return writable.get(); 
} 

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

例如:

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

上面的代码返回垃圾。 有没有解决这类问题的方法?

+0

什么是可写的? – cppcoder

+0

如果你没有遗漏代码,回答这个问题会更容易。 –

+0

@cppcoder boost :: scoped_array 可写(new char [newstr.size()+ 1]); – xybrek

回答

1

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

+0

我不能使用c_str()函数,因为我会得到这个错误:无法将参数2从'const char *'转换为'LPSTR'(char *) – xybrek

+0

您是否正在使用一些Win API功能? – undefined

+0

是的,我正在使用Win32应用程序 – xybrek

2

我要去承担writable是具有自动持续时间的对象,自毁它包含在析构函数的char* - 那是你的问题 - 无论writable.get()回报不再有效。

只需返回std::string而不是,为什么地球上你需要一个原始的char *

+0

我不能使用c_str()函数,因为我会得到这个错误:无法将参数2从'const char *'转换为'LPSTR'(char *) – xybrek

+0

@xybrek为什么bar'是char * ?你在修改字符串吗?你需要修改字符串吗? –

+0

char *是需要在我的应用程序中的某个函数上传递的参数 – xybrek