Search code examples
c++compiler-warningstemporary

Warning: returning reference to local temporary (But I can guarantee it's NOT a temporary)


I have a function get which returns a reference to an object. This function is called by an other function get2, which forwards this reference. In get2, the result of get is considered as a temporary, which is true. BUT I can guarantee that data behind that reference is not a temporary.

The following code reproduces the problem:

char * buffer; // for raw binary data, will be allocated somewhere

const char& getRaw(int idx){
    return buffer[idx];
}

const int& getInt(int idx){
    return getRaw(idx);
}

What should I do in that case? (In the meanwhile, I can even post a solution, but as long as its on hold, I can not answer it.)


Solution

  • To an experienced C++ programmer, the problem should be quite obvious: I implicitly convert from char& to int& in getInt. So the compiler will create a temporary int and return a reference to it, instead of just returning the char& and re-interpret it as an int&.

    A reinterpret cast helps:

    char * buffer; // for raw binary data, will be allocated somewhere
    
    const char& getRaw(int idx){
        return buffer[idx];
    }
    
    const int& getInt(int idx){
        return reinterpret_cast<const int&>(getRaw(idx));
    }