johan.ekman@gmail.com wrote:
[color=blue]
> I found a function in our code with a similar principle as:
>
> const char* MyString() const
> {
> return "Hello!";
> }
>
> I believe this function is wrong because "Hello" string would be
> allocated locally on the stack ?!?[/color]
No. Note that the only "stack" that C++ knows about is the standard class
std::stack. There is no need for a C++ implementation to store local
variables on any kind of stack.
Also, string literals have static storage duration. They exist until the end
of the program execution. When the function is called, a pointer to the
first element of that literal is returned, and that pointer is perfectly
valid.
[color=blue]
> (right) and therefore the method would return a pointer to an object that
> not exists outside this method.
>
> Doesn't that mean that a call such as:
>
> sprintf( MyString() );
>
> might output nonsense ?[/color]
No.