2015-10-05 91 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是你的朋友,你應該明白這一點。