The following code rises the warning: warning C4172: returning address of local variable or temporary but it makes no sense to me as the return type is a constant reference of the same type returned by std::vector::operator[] and std::vector::at().
Do you have an explanation for it?
#include <iostream>
#include <vector>
template <class V>
const V &at(const std::vector<V> &p_vec, const std::size_t p_index, const V &p_default) {
if (p_vec.size() <= p_index) {
return p_default;
}
return p_vec[p_index]; // warning C4172: returning address of local variable or temporary
}
int main(){
std::vector<bool> the_vector;
bool val = at(the_vector, 2, false);
if (val){
std::cout << "TRUE" << std::endl;
}else{
std::cout << "FALSE" << std::endl;
}
return 1;
}
Sample project: https://godbolt.org/z/KW5qo5YnK
>Solution :
The compiler is right to warn about this, because std::vector<bool>::operator[] returns std::vector<bool>::reference, which is not a reference to a bool. It is an implementation defined proxy type. The proxy can be converted to bool and thats the temporary the compiler mentions.
std::vector<bool> is specified such that it encourages implementations to pack 8 bools into a single byte. Hence operator[] cannot return a reference to bool.
You can specialize the function template for V==bool, or simply return a value.