简体   繁体   中英

const issue with pointer to pointer

I have a function that i'm using to delete buffers. The pointers are passed by address so that the function can also unset them once the memory is released :

static void _FreeBuf( const uchar16_t ** pBufPtr );

void Ucs2String::_FreeBuf( const uchar16_t ** pBufPtr );
{
   assert( NULL != pBufPtr && NULL != *pBufPtr );

   delete[] *pBufPtr;
   *pBufPtr = NULL;
}

But when using it as follows :

_FreeBuf( & m_wsBuf );

Where m_wsBuf is a member : uchar16_t * m_wsBuf;

It generates an error :

Error   1   error C2664: 'core::Ucs2String::_FreeBuf' : cannot convert parameter 1 from 'uchar16_t **__w64 ' to 'const uchar16_t **'

Removing the const fixes the issue, but I don't understand why. The function is modifying the pointer passed by address, not the const uchar16_t array pointed to, so why do I need to remove this const ?

PS : I'm using VS2005 (and no C++11)

The issue here is when you call the _FreeBuf( & m_wsBuf ); function: you try to convert a X** to a const X** (here X is uchar16_t , but the error would have occured no matter what the type is).

This is forbidden in C++ when this type of conversion is done implicitly (ie without const_cast ).

You can fix this either by removing const , or by changing the parameter type to const uchar16_t * const* (which wouldn't work in this case since you could not set the pointer to NULL in your function).

For more info about the reason why C++ works that way, see this link .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM