const_cast<char*>(Text.c_str())
#include<iostream>
#include<string>
#include<vector>
using
namespace
std;
void
some_func(
char
* s)
{
s[0] =
'X'
;
cout<<s<<endl;
}
int
main()
{
string myStr =
"hello"
;
vector<
char
> str(myStr.begin(), myStr.end());
str.push_back(
'\0'
);
some_func(&str[0]);
return
0;
}
Does the unpleasant C library function alter the data? If not, then simply
cast away the constness.
If it does, then you have to consider:
(1) Is it okay to alter the data at the address specified by c_str?
If so,
(1.a) Just cast away the constness and let it be altered.
If not,
(1.b) You'll have to make a copy.
The std::string manages it's own memory internally which is why, when it returns a pointer to that memory directly as it does with the c_str() function it makes sure it's constant so that your compiler will warn you if you try to do something incredibly silly like attempt to change it.
Using const_cast in that way literally casts away such safety and is only an arguably acceptable practice if you are absolutely sure that memory will not be modified. If you can't guarantee this then you must copy the string and use the copy; it's certainly a lot safer to do this in any event.
Here's a variation of 7stud's safe approach:.
Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
#include <iostream>
#include <string>
#include <vector>
namespace
{
char
* GetNonConstStr(
const
std::string& s)
{
//return non-constant copy of s.c_str()
static
std::vector<
char
> var;
var.assign(s.begin(),s.end());
var.push_back(
'\0'
);
return
&var[0];
}
void
someCFunction(
char
* str)
{
std::cout<<str<<std::endl;
}
}
int
main()
{
std::string s(
"hello world"
);
std::string t(
"hello multiverse"
);
someCFunction(GetNonConstStr(s));
someCFunction(GetNonConstStr(t));
|