Reputation: 10808
I have a problem understanding why a certain implicit conversion is not working as I expect it. I have the following class
ref class ManagedWStringArrayWrapper
{
wchar_t** m_pointer;
public:
operator wchar_t**()
{
return m_pointer;
}
};
and I thought this would implicitly convert to const wchar_t ** as well - but it doesn't. Can someone tell me why?
Upvotes: 3
Views: 581
Reputation: 46579
Because those are different things. If you look, for instance, at the C++ libraries, you'll find that there are often two functions for doing the same thing, one operating on const pointers and the other on non-const. Example.
But you can easily add an explicit operator const wchar_t**
.
Upvotes: 0
Reputation: 385204
Conversion from T**
to T const**
is not as intuitive as you might expect — in fact, it's given as an example in the standard itself as const
-incorrect code.
The example given is:
#include <cassert>
int main() {
char* p = 0;
//char const** a = &p; // not allowed, but let's pretend it is
char const** a = (char const**)&p; // instead force the cast to compile
char const* orig = "original";
*a = orig; // type of *a is char const*, which is the type of orig, this is allowed
assert(p == orig); // oops! char* points to a char const*
}
Study the above scenario for a while and it will become clear that this is not the same as a conversion T*
→ T const*
. Not at all!
I asked the same question in a blog post, and the FAQ has an entry on it too.
Upvotes: 3