J
Julie
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;
The above:
- doesn't use any pointers that must be manually deallocated
- is 100% portable(?)
- is 100% conformant(?)
I've seen Bjarne's similar implementation, but it uses new char * instead of
vector (obviously written before the STL was adopted).
auto_ptr<char> in place of vector<char> doesn't work because it doesn't handle
arrays.
Does anyone have comments on the above, specifically as to its suitability for
the requirements defined?
(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;
The above:
- doesn't use any pointers that must be manually deallocated
- is 100% portable(?)
- is 100% conformant(?)
I've seen Bjarne's similar implementation, but it uses new char * instead of
vector (obviously written before the STL was adopted).
auto_ptr<char> in place of vector<char> doesn't work because it doesn't handle
arrays.
Does anyone have comments on the above, specifically as to its suitability for
the requirements defined?