is there a runtime error here when you call the get method?
Code:#include <string> using namespace std; class A { public: string& get() { string abc = "abc"; return abc; } };
is there a runtime error here when you call the get method?
Code:#include <string> using namespace std; class A { public: string& get() { string abc = "abc"; return abc; } };
Why not just test and see? Of course, even if you do not get a runtime error, returning a reference to a local variable is still wrong.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
Why not just test and see? Of course, even if you do not get a runtime error, returning a reference to a local variable is still wrong.
Are you sure that even for a arge system we get an error?
Large or small, it does not matter. It is wrong since the caller would refer to an object that no longer exists.Are you sure that even for a arge system we get an error?
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
Runtime error? That should return a compiler error or warning.
Whatever you may say, returning a local variable is always wrong.
What is your rationale for wanting to know if there is such a guarantee?The question here is that is getting a runtime error a garuntee?
To confirm that: I get a compiler warning on the MinGW port of g++ 3.4.2.That should return a compiler error or warning.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
I believe what you'll get in that case is 'undefined behavior'. You might be able to reference the memory of the string you returned and it might work fine if that memory hasn't been overwritten; but then again, it could quite easily blow up (if you're lucky).
So the simple answer is: Don't use variables beyond their lifetime.