【发布时间】:2016-01-02 10:52:04
【问题描述】:
目前我在 C++ 中有这段代码(我使用的是 Visual Studio 2013):
char * dest= new char[srcLen + 1] {};
strcpy(dest, source);
std::string s(dest);
delete dest;
如何使用 make_unique 将其转换为 C++11 unique_ptr 以便 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。我已经更新了我的代码 sn-p 以使其更加清晰。基本上,源 char * 数组可能会或可能不会以 null 结尾。临时的dest 缓冲区确保字符串以空值结尾。我确实想将其转换为std::string。我之前的工作。我只是想知道是否有办法使用make_unique 创建临时缓冲区,这样就不需要new 和delete。
【问题讨论】:
-
我有兴趣了解更多关于导致您决定为此使用
std::unique_ptr的思维过程。 -
我更新了我的帖子来解释我的推理。谢谢。
-
仍然没有解释你为什么使用
new/delete,以及为什么你现在使用std::unique_ptr。哦,好吧。 -
@LightnessRacesinOrbit 我想我想看看使用
unique_ptr创建动态字符数组是否有意义,因为我不必担心删除它,但我想不是。跨度> -
将
new/delete替换为std::unique_ptr是有意义的,是的,但我怀疑new/delete首先是否适合您的问题,然后转到std::unique_ptr只会让你走得更远。为什么不直接从原始数据构造一个std::string并完成它呢?如果需要,在事后手动剥离可选的空终止符。
标签: c++ c++11 visual-studio-2013 unique-ptr