目前我有這樣的代碼在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'。好吧。 –