scope

hi guys this a similar question to my array question but differs slightly so I said I'll open another thread

anyway this example is perfectly legal

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  #include <iostream>
using namespace std;

string foo(){

	string f = "ABC";
	return f;
}


int main() {

    const string &fo = foo();

	cout << fo << endl;


}


const string &fo binds the object returned to a temp object and exists until the reference fo goes out of scope


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22


#include <iostream>
using namespace std;

string&  foo(){

	string f = "ABC";
	return f;
}


int main() {

    const string &fo = foo();

	cout << fo << endl;


}



but now with the code above when I return a reference and bind it to a const reference prolonging the life the program crashes(every time) but compiles fine

and also side note how come you can prolong the life of an object by making it a const reference but not do the same with pointers?


thanks
Hello adam2016,

I am not saying I am the best at this, but I will give it a try.

As I understand this in the second example "foo" is returning a reference to variable "f" which goes out of scope and is destroyed when the function ends. So, back in main you are trying to use reference to a variable that no longer exists.

In main line 15 "const" does not affect the function in any way that I know of. it does say that you can not change the value of "fo" in main.

In the function "foo" making "f" on line 8 "static" allowed the program to work.

Sorry if I am not as accurate as I should be, but that is what I see.

Hope that helps,

Andy
Topic archived. No new replies allowed.