Created
March 22, 2015 17:37
-
-
Save hi2p-perim/0cb7b33383ad7c6df3de to your computer and use it in GitHub Desktop.
dynamic_cast with unique_ptr
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
This leaks memory.
@MaxKellermann where, and how would you improve it?
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
.
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
I came to the same conclusion, thanks :)