Skip to content

Instantly share code, notes, and snippets.

@hi2p-perim
Created March 22, 2015 17:37
Show Gist options
  • Select an option

  • Save hi2p-perim/0cb7b33383ad7c6df3de to your computer and use it in GitHub Desktop.

Select an option

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
Copy Markdown

I came to the same conclusion, thanks :)

@MaxKellermann

Copy link
Copy Markdown

This leaks memory.

@sebkraemer

Copy link
Copy Markdown

@MaxKellermann where, and how would you improve it?

@MaxKellermann

Copy link
Copy Markdown

If the dynamic_cast fails, it returns nullptr, means b1 is not set, but a1 has already been released, and the object previously pointed-to by a1 is owned by nobody, and thus leaks.
Cast first, and only if it succeeds you may release a1.

@sebkraemer

Copy link
Copy Markdown

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