Saturday, October 17, 2015

Digest for comp.lang.c++@googlegroups.com - 2 updates in 1 topic

"Alf P. Steinbach" <alf.p.steinbach+usenet@gmail.com>: Oct 17 06:29AM +0200

On 10/16/2015 9:35 PM, Christopher Pisz wrote:
>> for( auto& p : types ) { p = things.c_str(); }
 
> p = things.c_str();
 
> Assigning std::string::c_str() to type char * does not work.
 
ITYM, "assigning std::wstring::c_str() to type char* does not work". The
solution to that involves using the Unicode API functions, not the
1990's Windows ANSI functions. Define the macro symbol UNICODE before
including <windows.h>. Use wchar_t, not char. Remember to add const as
appropriate: assigning std::wstring::c_str() result to wchar_t* is not
valid, but wchar_t const* is OK.
 
 
> When the
> string goes out of scope, so does its buffer, I believe.
 
Yes. Don't let the vector with the strings go out of scope yet.
 
Quting myself on that, "You do need to be careful with zero size array
and lifetimes and modifying operations and such.".
 
I.e., there are also a few more such possible pitfalls.
 
 
> The vector has to have each element point to allocated memory, or where
> are we going to store the string?
 
Uh, I think this refers to some flawed understanding.
 
Maybe that has to do with failing to quote the relevant declarations, above.
 
 
> Nor does variable 'things' have a c_str() method, it's a vector. So, the
> for(auto...syntax can't be used, because you need an index, no?
 
It can be used, with some backing (e.g. à la Python's enumerate), but
since you don't have that already in your toolbox it's simpler to just
use an index-based loop. Sorry for just sketching the code.
 
 
Cheers & hth.,
 
- Alf
mark <mark@invalid.invalid>: Oct 17 09:28AM +0200

On 2015-10-16 20:02, mark wrote:
> delete[] data;
> return out;
> }
 
There is a performance bug in the code. The emplace_back call creates a
temporary string + copy.
 
std::vector<std::string> ConvertAndCleanup(char** data)
{
std::vector<std::string> out;
for(char** elem_ptr = data; *elem_ptr != nullptr; ++elem_ptr) {
out.emplace_back(*elem_ptr);
delete[] *elem_ptr;
}
delete[] data;
return out;
}
You received this digest because you're subscribed to updates for this group. You can change your settings on the group membership page.
To unsubscribe from this group and stop receiving emails from it send an email to comp.lang.c+++unsubscribe@googlegroups.com.

No comments: