tags:

views:

107

answers:

2
#include "iostream"
#include "vector"
using namespace std;

const vector<int>& Getv() 
{
vector<int> w(10);
w[0]=10;
cout<<w.size()<<endl;
return w;
}
//Now when I write in main:
vector<int>v = Getv();//Throws exception
//and the below rows has no effect
vector<int>v;
v=Getv()//w does not change

please what is the problem?
Hani Almousli...

+9  A: 

You're returning a reference to a local variable. When you exit the function it gets destructed.

You need to return a copy:

vector<int> Getv() 
{
  vector<int> w(10);
  w[0]=10;
  cout<<w.size()<<endl;
  return w;
}

Or you could make w static:

const vector<int>& Getv() 
{
  static vector<int> w(10);
  w[0]=10;
  cout<<w.size()<<endl;
  return w;
}

Also you should use <> on your includes since they're part of the standard library.

Bruce
or return a pointer.
Tom
Hani
Tom
Hani
You got lucky, undefined behavior means it could work the way you wanted it to but that's not always the case.
Bruce
Hani, just because it worked on your machine this time on this run doesn't mean it's correct. You cannot return a reference to a local-stack allocated object, because when the function ends, it will go away. Static variables live in-between function calls.
GMan
Of course, returning a pointer to a local object is just as bad :)
UncleBens
Tom Leys
+1  A: 

It seems that you confuse return parameter and input argument. It's safe to pass argument by constant reference:

void fun(const vector<int>& arg1)
{
    //something
}

In that example you pass only reference, so copy constructor isn't invoked.

But it's dangerous to return reference value (const or not const) from function. See answer of Bruce above. Also you can extend reference lifetime:

const vector<int>& Getv() 
{
    vector<int> w(10);
    w[0]=10;
    cout<<w.size()<<endl;
    return w;
}

const vector<int>& v = Getv(); //now all ok

But I don't recomment this way. It can be source of future bugs. The best way is returning value of vector.

vector<int> Getv() 
{
   vector<int> w(10);
   w[0]=10;
   cout<<w.size()<<endl;
   return w;
}

vector<int>v = Getv();

Since there is only 1 return statement you can account for RVO and copy constructor won't be invoke too. it is fast and safe.

AlexeyBor