2015-10-05 81 views
-2

目前我有这样的代码在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创建临时缓冲区,以便不需要newdelete

+1

我想了解更多关于思​​考过程的信息,这些思维过程导致您决定为此使用'std :: unique_ptr'。 –

+0

我已更新我的帖子来解释我的推理。谢谢。 – Ionian316

+0

仍然没有解释为什么你为此使用'new' /'delete',以及为什么你现在使用'std :: unique_ptr'。好吧。 –

回答

4

不要。

使用std::string,该类型设计用于包装动态分配的char数组。

更一般地,你可以与T* std::unique_ptr<T>::get() const成员函数访问std::unique_ptr的根本指针:也

strcpy(dest.get(), source); 

,你有一个错误你也正在和dest做的是建立一个单一的动态分配char,初始值为srcLen。哎呦!

与往常一样,the documentation是你的朋友,你应该明白这一点。