将char数组转换为C ++ 11 unique_ptr for strcpy

时间:2015-10-05 17:27:40

标签: c++ c++11 visual-studio-2013 unique-ptr

目前我在C ++中使用此代码(我使用的是Visual Studio 2013):

char * dest= new char[srcLen + 1] {};
strcpy(dest, source);
std::string s(dest);
delete dest;

如何使用unique_ptr将其转换为C ++ 11 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 *数组可能会或可能不会被终止。临时dest缓冲区确保字符串以空值终止。我确实想将其转换为std::string。我之前的作品。我只是想知道是否有一种方法可以使用make_unique创建临时缓冲区,这样就不需要newdelete

2 个答案:

答案 0 :(得分:4)

<强>不

使用int nslen = strlen(number_string); for ... number_string[nslen++] = temp number_string[nslen] = '\0'; ,这是专为包装动态分配的std::string数组而设计的类型。

更一般地说,您可以使用char成员函数访问std::unique_ptr的基础指针:

T* std::unique_ptr<T>::get() const

此外,您还有一个错误,就是您现在正在使用strcpy(dest.get(), source); 创建一个动态分配的dest,其初始值为char。糟糕!

与往常一样, the documentation是您的朋友,您绝对应该这样对待。

答案 1 :(得分:0)

我有一个类似的问题,我需要转换一些旧代码以使用std::string,但是它与许多其他功能绑定在一起,所以我不能完全重构所有内容。在某个时候,我一直将字符串作为char数组处理。

我发现的解决方案是创建一个指向char []数组的唯一指针,并将strpyc_str()插入到数组中。显然,我不能用它来更新实际的字符串,因为它是只读的,但这不是必需的。

这是代码:

std::unique_ptr<char[]> temp_a_local_string(new char[a_local_string.length()+1] {0});

strcpy(temp_a_local_string.get(), a_local_string.c_str());

pa_local_string = temp_a_local_string.get();

从那里开始,pa_localstring(原始变量)被视为旧的char数组。此后不久,它就超出了范围,因此unique_ptr消失了。

我可能应该使用make_unique,但是我还不熟悉自动指针。