I have some code written by someone else in which some functions take arguments whose data types are followed by a *&. I'm used to functions taking one or the other, e.g. taking a "double *" or a "double &" but not both. It would have thought they would just cancel out.
Here's an example, and this is all from their code which supposedly works:
In a header file there's a function declared as:
void someClass::foo(const unsigned int*& ubuff);
Then in my main file, there's a pointer to some UINTs declared and initialized as:
unsigned int* pbuff = new UINT[n];
Then, the function someClass::foo is called as:
foo(pbuff);
When I compile, I get the error "cannot convert parameter 1 from 'unsigned int *' to 'const unsigned int *&'". If I change my function call to the following, it compiles ok:
foo((const unsigned int *&)(pbuff));
So, my questions are:
What is the purpose of the *&? I.e., how is that different from * or & by themselves, and why do they not just cancel themselves out? And what does that make the function foo expect? An address? A value? The address of an address? It's confusing.
Is the fix of simply casting a "unsigned int*" to a "const unsigned int*&" ok or do I need to do something else?
Just another quick example, and this is from completely within a cpp file distributed by someone else, so I assume this compiled for them. They have a function call as
klabels = new int[sz];
EnforceLabelConnectivity(klabels, m_width, m_height, nlabels, numlabels, double(sz)/double(STEP*STEP));
When I try to build, I get an error "'SLIC::EnforceLabelConnectivity' : cannot convert parameter 1 from 'int *' to 'const int *&'".
Thank开发者_如何学Pythons as always.
For a type T, T *&
means "a reference to a pointer to a T." The calling function should pass a pointer to a T. As to the const modifier, try foo((const unsigned int *)pBuff);
or else declare pBuff to be a pointer to a const int to start with.
Well, I tried casting to a (const unsigned int *), and that did not work (wouldn't build). In the end, I had to fully cast to a (const unsigned int *&) in the foo function example in my original post. Hope this helps. Thanks.
As an aside, the reason I did not go the route of making pbuff const from the beginning in my main code is that it is passed to another function later on which does modify it, so I don't think it would work to have it made const when declared.
- Pointers and references are really differents, but using a reference to a pointer is kind of useless.
- This is not ok, pbuff is not const that's why your code doesn't compile. Use a const pbuff or change your prototype, casting like this is really ugly
精彩评论