Markus Dehmann wrote:[color=blue]
>[color=green]
> > It's unclear what you want to do here. If you want to assign the value
> > of the new string into the old string in the parent you can do:
> >
> > *s = newString;[/color]
>
> That works. The *s instead of s does the trick.[/color]
Yep.
But your further reply shows that you haven't understood what it does.
's' is a pointer to a string.
This pointer is passed from main, and points to the string 'main::s'
(That is variable s in main).
'*s' dereferences that pointer and thus you get a hand on the string
object itself.
*s = That string object (the one in main, because this is where this
pointer points to) gets a new value.
*s = newString; In particular it gets a copy of the value in newString
[color=blue]
>
> I'm surprised though, that this is valid code. I thought newString will be
> destroyed at the end of the modify function:
>
> void modify(string* s){
> string newString = "test";
> *s = newString;
> }
>
> It goes out of scope.[/color]
It doesn't matter.
When newString runs out of scope, its value has long been copied to the string
object where s points to (and that is the string variable s in main).
[color=blue]
> So, if I say *s=newString, and access s later, from
> the main() function, isn't that undefined behavior, because s points to
> someting that has gone out of scope?[/color]
In that function, s always points to the same memory object. And that is the
variable s in main(). It never points to something else.
When you say:
*s = ...
you are changing the object where s points to. You are not changing where
s points to. If you want to change where s (the pointer in modify()) points
to you simply would do
s = ...
(But note: 's' in modify() is a local variable, so changing where this pointer
points to has no effect on the caller)
--
Karl Heinz Buchegger
kbuchegg@gascad.at