简体   繁体   中英

Convert char array to C++11 unique_ptr for strcpy

Currently I have this code in C++ (I'm using Visual Studio 2013):

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

How do I convert this to a C++11 unique_ptr using make_unique so that it's usable by strcpy() ?

I tried:

auto dest = make_unique<char>(srcLen + 1);
strcpy(dest, source);

However, I'm getting the following compile error on the strcpy line

Error   1   error C2664: 'char *strcpy(char *,const char *)' : cannot convert argument 1 from 'std::unique_ptr<char,std::default_delete<char>>' to 'char *'

Update I do use a std::string . I've updated my code snippet to make it more clear. Basically, the source char * array may or may not be null terminated. The temporary dest buffer ensures that the string is null-terminated. I do want to convert it to a std::string . What I had before works. I just wanted to know if there's a way to create the temp buffer using make_unique so that there will be no need for new and delete .

Don't.

Use a std::string , the type designed for wrapping dynamically-allocated char arrays.

More generally, you may access the underlying pointer of a std::unique_ptr with the T* std::unique_ptr<T>::get() const member function:

strcpy(dest.get(), source);

Also, you have a bug in that all you're doing with dest right now is creating a single dynamically-allocated char , with initial value srcLen . Whoops!

As always, the documentation is your friend and you should definitely treat it as such.

I had a similar problem, I needed to convert some old code to use std::string but it's got tie-ins from lots of other functions so I can't just completely refactor everything. At a certain point, I'm stuck dealing with the string as a char array.

The solution I found was to make a unique pointer to a char[] array and strpy from the c_str() into it. Obviously I can't use that to update the actual string as it's read-only but that wasn't a requirement.

Here's the code:

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();

And from there, pa_localstring (which was the original variables) is treated like the old char array. It goes out of scope pretty soon after, and thus dies the unique_ptr .

I probably should be using make_unique , but I'm not super-versed in auto pointers yet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM