Skip to content

Instantly share code, notes, and snippets.

@hi2p-perim
Created March 22, 2015 17:37
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hi2p-perim/0cb7b33383ad7c6df3de to your computer and use it in GitHub Desktop.
Save hi2p-perim/0cb7b33383ad7c6df3de to your computer and use it in GitHub Desktop.
dynamic_cast with unique_ptr
#include <iostream>
#include <memory>
struct A
{
virtual ~A() {}
};
struct B : public A
{
};
int main()
{
std::unique_ptr<B> b(new B);
std::unique_ptr<A> a(b.release());
std::unique_ptr<A> a1(new B);
std::unique_ptr<B> b1(dynamic_cast<B*>(a1.release()));
// Error
//std::unique_ptr<A> a2(new B);
//std::unique_ptr<B> b2(a1.release());
return 0;
}
@sebkraemer
Copy link

Yeah OK, so in general this approach could leak, that's true.
Thanks for the clarification.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment