To solve a very peculiar problem in my application I need a shared-pointer to allocated data, but to the outside world, the underlying data type should remain hidden.
I could solve this by making some kind of Root class of which all my other classes inherit, and use a shared_ptr on this Root class, like this:
std::shared_ptr<Root>
However:
- I don't want all my classes to inherit from this Root class just to be able to have this shared pointer
- Sometimes I want to return a shared pointer to std::vector, or std::list, or std::set, ... which obviously don't inherit from my Root class
Strange enough, it seems that you can create a shared_ptr on void and this seems to work correctly, like shown in this example:
class X
{
public:
X() {std::cout << "X::ctor" << std::endl;}
virtual ~X() {std::cout << "X::dtor" << std::endl;}
};
typedef std::shared_ptr<void> SharedVoidPointer;
int main()
{
X *x = new X();
SharedVoidPointer sp1(x);
}
x is correctly deleted and in a larger experiment I could verify that the shared pointer does indeed what it needs to do (delete x afer the last shared_ptr turns out the light).
Of course this solves my problem, since I can now return data with a SharedVoidPointer data member and be sure that it's correctly cleaned up where it should be.
But is this guaranteed to work in all cases? It clearly works in Visual Studio 2010, but does this also work correctly on other compilers? On other platforms?
See Question&Answers more detail:os