1

I've tried the following:

std::string* Member::GetName()
{
    std::string name2 = "sdfsdfsd";
    return &name2;
}

std::string* name;
Member m;

name = m.GetName();

std::cout << *name  << std::endl;

and it "works", but shouldn't be name2 unavailable after GetName() is called? and my pointer points to nothing?

Edit:

Coming back after years with more exp. some already answered this question below.

Returning a local is bad!, you might get away with it, if the value on the stack didn't get overwritten, so often when you directly use it after returning a local you might get the correct values, but this is still undefined behaviour. Also not returning a const& also doesn't work, even now sometimes i think it binds the return value to a temporary as it does for const& parameters, but thats not the case for return types, the same goes for returning r-values refs. you can only return a copy and get it as const ref like this

std::string GetName();

const std::string& name  = GetName();

this will bind it to a temporary therefore is valid check herb sutters gotw: https://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/ for const ref temporaries.

5
  • 1
    This really isn't safe Commented Oct 15, 2014 at 8:26
  • why does it even work? Commented Oct 15, 2014 at 8:26
  • 1
    It only appears to work in this limited context. Commented Oct 15, 2014 at 8:28
  • Cause you are lucky "this time". It's UB. Commented Oct 15, 2014 at 8:29
  • @Sleicreider - why does it even work? It did "work". Crashing would also "work", running on your computer and crashing on someone else's would also "work". That's what "undefined behavior" is all about. Commented Oct 15, 2014 at 8:38

1 Answer 1

3

Taking the address of a local stack variable and using it when it's no longer in scope it's undefined behavior.

As for "it works", it doesn't mean it will always work or that is a reliable practice. The stack isn't immediately wiped out when returning. Take a look at the definition of "undefined behavior"

Sign up to request clarification or add additional context in comments.

1 Comment

well i would never write such code, I were just surprised why it gave me the right value, but thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.