string advice

N

Noah Roberts

I have a situation in which a function expects a char const* and uses
the supplied address directly. It's a GUI element in a particular
platform but the question is generic.

I could give it the c_str() return of the string and expect that the
string isn't going to change, if it does send the c_str() again.

I could give it &str[0].

I could use a vector and do the same as the second string method.

I could also just use a raw array but I see no real advantage in that.

From a portability or design standpoint is there any /real/ difference
in the first three choices?
 
A

Alf P. Steinbach

* Noah Roberts:
I have a situation in which a function expects a char const* and uses
the supplied address directly. It's a GUI element in a particular
platform but the question is generic.

I could give it the c_str() return of the string and expect that the
string isn't going to change, if it does send the c_str() again.

I could give it &str[0].

I could use a vector and do the same as the second string method.

I could also just use a raw array but I see no real advantage in that.

From a portability or design standpoint is there any /real/ difference
in the first three choices?

The c_str() result is only guaranteed to be valid as long as the
std::string instance exists and no mutating operations are performed.
This may matter if the GUI element doesn't copy the string.

&str[0] is not guaranteed to be zero-terminated. Pedantically, under
the current standard it's not guranteed to be a pointer to a contiguous
buffer, either, but for all practical purposes you can ignore that.

A vector has the advantage that folks not familiar with the standard's
evolution and existing compiler practice, may not think you're doing a
dangerous thing (they'll think, rightly, that the buffer is contiguous).
It has the disadvantage that if the string comes from elsewhere in the
form of a std::string, you'll have to copy the data.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,677
Members
48,796
Latest member
Greg L.

Latest Threads

Top