First I think the following is definitely Undefined Behavior:
Object & foo(){
Object o;
return o;
}
Object & ref = foo();
But now suppose a function that takes a reference of another object which will exists longer, and assign this reference to a local variable, and the local variable gets out of scope. Would the reference of this object also be destroyed as the local variable is destroyed?
class b {
public:
int val;
b& round() {
val += 2;
return *this;
}
int operator+(int i) const{
return val + i;
}
};
template<typename T>
class A {
public:
typedef typename std::vector<b>::const_reference const_reference;
typedef typename std::vector<b>::reference reference;
vector<b> _a;
A() {
_a.resize(10);
}
inline const_reference set() const {
return _a.at(0);
}
inline reference set() {
return _a.at(0).round();
}
};
void func1(A<int>& a) {
b tmp = a.set();
tmp.val = tmp.val + 2;
cout << a._a[0].val << endl;
}
int main() {
A<int> a;
a.set();
func1(a);
cout << a._a[0].val << endl;
}
Basically reference to _a[0] is assigned to tmp in func1.
I am doing it this way because I have concerns that _a[0] would be destroyed as tmp goes out of scope, But I want to return a reference so that I can use it as an lvalue, assigning rvalues directly to it, like doing
a.set() = 1;
Another point is that I am forced to write another set() const function and return a const reference.
I am forced to write the const keyword in another set because in another function, for example func2, I passed input as a const vector reference, but my usage is not modifying it. However, without the set() const method, the compiler errors when calling func2 (input,output).
No matching function for call to object of type 'const vector<A>.The argument has type const but the method is not marked const.
void func2(const vector<A>& input, vector<A>& output) {
int sum = input[0].set() +2;
}
To me, things involving const rules become very tricky. So to solve this situation, I am thinking of copying input[0].set() to a local tmp first and do the addition.
So going back to the original question:
Would the local variable containing the reference destroy the reference itself when it goes out of scope? i.e. b tmp = a.set(); when tmp is out of scope from func1, nothing changes on a or a._a[0], or a._a[0] would also be released because tmp is a reference to a._a[0]?
Excuse me for being verbose... things are getting very complex and tough by the time I know and try to learn template programming and const of C++... So I am trying to have the flexibility to sometimes use the set() as a reference for lvalue assignment and sometimes I also want to use it just as an rvalue.