First I think the following is definitely UB.
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 destroed as tmp goes out of scope, but I want to return a reference so that I can use it as a 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 returns a const reference.
I am forced to write the const key word 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.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 involved const rules become very tricky. So to solve this situation, I am thinking 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 destroys the reference itself when it goes out of scope?
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 lval assignment and sometimes i also want to use it just as a rvalue..
Any help is appreciated!
Aucun commentaire:
Enregistrer un commentaire