Vector assignment problem
#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=Get开发者_开发百科v()//w does not change
please what is the problem?
Hani Almousli...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.
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.
精彩评论