"Alex Vinokur" <al****@go.to> wrote in message
news:di**********@reader.greatnowhere.com...
"mlimber" <ml*****@gmail.com> wrote in message
news:11*********************@g14g2000cwa.googlegro ups.com...
Alex Vinokur wrote: > I have got two functions:
>
> void foo1(char* str)
> {
> // Stuff
> }
>
> void foo2(int size)
> {
> char* str;
> str = new char[size];
> // Stuff-1
> foo1(str)
> // Stuff-2
> }
>
> Function foo1() can't be changed.
> Function foo2() can be changed.
>
> I would like to use string::c_str() instead of char* in new version of
> foo2();
> Something like:
>
> void new_foo2(int size)
> {
> string str(size, '0');
>
> // Stuff-1
> foo1(str.c_str())
> // Stuff-2
> }
>
> It seems to be problematic.
>
> Is there any appropriate solution?
In what way is it problematic? Compiler errors? Run-time errors? Speed
change? Please elaborate.
Cheers! --M
I think it is unsafe.
As Victor explained, if foo1 is going to change str, you should not pass
what c_str() returns.
But if foo1 documents that it doesn't change the contents of str, then it
should have been declared as
void foo1(char const *);
You can cover up foo1's problem by using const_cast:
void my_foo1(char const * str)
{
// We know that foo1 doesn't change the string
foo1(const_cast<char *>(str));
}
Now, instead of calling foo1, call my_foo1 everywhere:
string str("something");
my_foo1(str.c_str());
Ali