Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

`Returning address of local variable` on a C++ templated function with proper return type

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading