Returning containers from functions (memory issue)

Q1.

Consider the code snippet

1
2
3
4
5
6
7
8
9
10
11
int foo(vector<baz> & rick)
{
 int num;
 vector<baz> local;

 //process and add stuff to local
 //process num

 rick = local;
 return num;
} 


The vector local has been created inside the function, and we are assigning the reference rick from it.
When the function returns, isnt the vector local deallocated?


Q2. Let iter be a iterator

vector<int>::iterator iter = students.begin();

What happens if I try to access iter[-1]?
Last edited on
closed account (zb0S216C)
DexterMorgan wrote:
When the function returns, isnt the vector local deallocated?

Yes, unless declared static.

DexterMorgan wrote:
What happens if I try to access iter[-1]?

Undefined behaviour.

Wazzak
Last edited on
So, the vector local is deallocated but rick points to the deallocated vector.
Thus, I cannot use the vector rick?
Last edited on
rick = local; will make a copy of local so you can use the vector after the function without problems.
Last edited on
But rick is a reference variable, my understanding of reference variables that if
a reference variable is assigned an object, no copying of objects occur, only that the reference variable (here rick) is now an alias for the object (here local). What did I miss?
The object that the reference is referring to is decided when the reference is created and can't be changed later. Any action on the reference affects the original object.
1
2
3
4
5
int a = 0;
int b = 1;
int& r = a;
r = b;
// r is still referring to a and a is now equal to 1 
Last edited on
^I think you meant int& r = a; on line 3.
Yes I do. thank you.
Thanks!
I did not realize I had not understood references!!
That example makes it clear.
Topic archived. No new replies allowed.