dimanche 25 février 2018

returning reference to a pointer

I was looking at this link about returning reference to a pointer. According to this, we have to return reference to a static or global variable. My question here is, in case we create memory block inside a function using new, will it be a problem if we use a local variable since memory allocated using new is permanent until deleted? I wrote below code to test this and it seems to be working. But I am not really sure if such usage is a good practice or not.

int* &returnPtrByRef(int numElements)
{
    static int *ptr = new int(numElements);

    return ptr;
}
int main (void)
{
    int num=5;
    int *&ptrRef = returnPtrByRef(num);
    for(int cnt=0;cnt<num;cnt++)
    *(ptrRef+cnt) = cnt*2;
    for(int cnt=0;cnt<num;cnt++)
    cout<<*(ptrRef+cnt)<<'\t';
    return 0;
  }

Aucun commentaire:

Enregistrer un commentaire