I have two dummy questions which have confused me for a while. I did do some searching online and read through much c++ tutorials, however I cannot find concrete answers.
You can return pointer to local object, but it will be pointed to stack memory, so results may be suprising. Look the following code:
#include
using namespace std;
class Node { public: int n; };
Node* create(int n) {
Node node = Node();
node.n = n;
cout << "Created " << node.n << endl;
return &node;
}
int main() {
Node* n1 = create(10);
Node* n2 = create(20);
cout << "Reading " << n1->n << endl;
cout << "Reading " << n2->n << endl;
return 0;
}
You won't get "10" "20" output. Instead
Created 10
Created 20
Reading 20
Reading 1891166112
First object was destructed (when first create function call ended). Second object was created on top of destructed n1, so n1 address was equal to n2 address.
Compiler will warn you when you return stack addresses:
main.cpp: In function Node* create(int):
main.cpp:8:10: warning: address of local variable node returned [-Wreturn-local-addr]
Node node = Node();