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;
}
};
Printable View
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.
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.Quote:
Are you sure that even for a arge system we get an error?
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?Quote:
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.Quote:
That should return a compiler error or warning.
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.