目前我有这样的代码在C++(我使用Visual Studio 2013):转换字符数组到C++ 11的unique_ptr的strcpy的
char * dest= new char[srcLen + 1] {};
strcpy(dest, source);
std::string s(dest);
delete dest;
如何将它转换为一个C++ 11 unique_ptr
使用make_unique
以便它可以使用strcpy()
?
我想:
auto dest = make_unique<char>(srcLen + 1);
strcpy(dest, source);
但是,我得到的strcpy
线以下编译错误
Error 1 error C2664: 'char *strcpy(char *,const char *)' : cannot convert argument 1 from 'std::unique_ptr<char,std::default_delete<char>>' to 'char *'
更新我使用std::string
。我更新了我的代码片段,使其更加清晰。基本上,源char *数组可能或不可以以null结尾。临时dest
缓冲区确保该字符串以空字符结尾。我确实想将它转换为std::string
。我之前的工作。我只想知道是否有办法使用make_unique
创建临时缓冲区,以便不需要new
和delete
。
我想了解更多关于思考过程的信息,这些思维过程导致您决定为此使用'std :: unique_ptr'。 –
我已更新我的帖子来解释我的推理。谢谢。 – Ionian316
仍然没有解释为什么你为此使用'new' /'delete',以及为什么你现在使用'std :: unique_ptr'。好吧。 –