0

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)

Virus721
  • 8,061
  • 12
  • 67
  • 123
  • FWIW, in `C` you don't need a pointer to pointer to `free()` it. – Sourav Ghosh May 13 '15 at 09:21
  • Neither do I in C++. As i said i'm passing pointers by address so that they can be unset once the memory is released. – Virus721 May 13 '15 at 09:22
  • 1
    Unrelated, but don't use symbols with leading underscore followed by an upper-case letter, [those are reserved in all scopes](http://stackoverflow.com/a/228797/440558). – Some programmer dude May 13 '15 at 09:22
  • Mmmm i knew about the double underscores, but not this which i've always used for non-public things. Good to know. – Virus721 May 13 '15 at 09:24

1 Answers1

2

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.

BlackDwarf
  • 2,070
  • 1
  • 17
  • 22
  • Thanks for your answer. What i don't understand is why it is forbidden. Trying to convert const to non-const generates an error and that makes sense, but converting from non-const to const should not, and this is why i'm trying to do here. Also if i add a second const i won't be able to unset the pointer once i've deleted what it points to. EDIT ho didn't see the link, i'm gonna read this. – Virus721 May 13 '15 at 09:41
  • The link I provided in the answer explains why some non-const to const conversions result in errors. About adding the second const, you're right, in your case it wouldn't work since you could not set the pointer to NULL, it's just a general workaround for this issue. I edited my answer to make it clearer. – BlackDwarf May 13 '15 at 09:45