Domanda

When the following code is compiled by g++ or clang++, I get the warnings "returning reference to temporary object" (g++) and "returning reference to local temporary object" (clang++).

Can someone enlighten me as to why getData_warning exhibits these warnings, whereas getData_nowarning does not?

struct Geom {
    int * data;
};


// Not ideal because one can change the pointed to value
int * const & getData_nowarning (Geom const & geom) {
    return geom.data;
}


// Ideal because one cannot change the pointed to value.
int const * const & getData_warning (Geom const & geom) {
    return geom.data;    //   <-------------------  WARNING HERE
}


void test () {
    Geom const geom = { new int(0) };

    int * data1 = getData_nowarning(geom);

    int const * data2 = getData_warning(geom);
}
È stato utile?

Soluzione

Because the type of geom.data is int*, you cannot refer to it with a reference to int const*. In order to make a reference to an int const*, first you need an int const*. So there must be a conversion, so a new pointer of a new type must be created, and so it must be a temporary.

Do you need the caller of the function to be able to change what the pointer in the geom object points to? It would seem not, since you are making the pointer itself const. So just drop the reference, and you can keep the const.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top