J
Julie
Julie said:I'm re-evaluating the way that I convert from a std::string to char *.
(Requirement: the source is a std::string, the usable contents are char *)
Here is what I've come up with:
#include <string>
#include <vector>
#include <cstring>
// presume s from somewhere, such as:
std::string s = "<initial value>";
std::vector<char> v(s.length() + 1);
std::strcpy(&v[0], s.c_str());
char * c = &v[0];
// use c, where a char * is _specifically_ required
s = c;
So then, under the presumption that this is about as 'clean' as it can get,
does anyone have a comment on why a method for direct access wasn't provided in
the std::string implementation? I'd have presumed that something like that
would have been requisite to be more compatible w/ C and C-style strings and
interfaces.
Something like:
class string
{
private:
char * _accessbuf; // NULL initialized in constructor
public:
char * string::access(const size_t num_chars)
{
delete [] _accessbuf;
_accessbuf = new char[num_chars+1];
copy(_accessbuf, num_chars, 0);
_accessbuf[num_chars] = '\0';
return _accessbuf;
}
void string::commit(const bool commit=true)
{
if (_accessbuf)
{
if (commit)
{
*this = _accessbuf;
}
delete [] _accessbuf;
_accessbuf = NULL;
}
}
// etc.
};
Then, accessing C-style interfaces would resolve to:
GetFileName(str.access(_MAX_PATH), _MAX_PATH);
str.commit();
instead of the cumbersome method in my original post.
Comments?
(Note: the names access and commit are completely arbitrary, more appropriate
names probably exist.)