Advantage and disadvantage of using void pointer in C++ pimpl
I am trying to study the pimpl technique for C++. After went through some articles online, I found there are two different ways for pimpl, one is
class X
{
public:
X(...parameters...)
~X()
private:
struct Impl;
Impl* impl_;
};
The other way is to use a raw void pointer, like
class X
{
public:
X(...parameters...)
~X()
private:
void * impl_;
};
Then use static_cast to cast the void pointer back to the original type.
What are the advantages and disadvantages comparing these two ways?
Thanks!
Do not use void*
for implementing a pimpl, or for much of anything for that matter. It provides no benefits; and has the potential problem where if you static_cast
to the wrong type for some reason, you will have undefined behaviour.
It's easy to forward-declare your implementation class, as you have in your first example. That is the correct way to implement a pimpl.
With the first one, using a debugger you will be able to view the impl pointer and it's data members values. If you have a void*
pointer, you won't be able to do that.The second option doesn't offer any advantage that I know of.
Either way, if you have
Impl* GetImpl() { return impl_; }
or
Impl* GetImpl() { return static_cast<Impl*>(impl_); }
Both functions will generate exactly the same assembly code.
If you don't need a getter, you could instead have it like: struct Impl* impl_;
as well.
上一篇: C#结构体/类堆栈/堆控制?