Use std::unique_ptr
:
auto aScopedPtr = make_unique<MyType>();
// lots of logic here
if (condition)
iPtrVector.push_back(aScopedPtr.release());
You can search around for an implementation of make_unique
to copy and paste. You can use:
std::unique_ptr<MyType> aScopePtr{ new MyType() };
If you really have to, but strongly prefer make_unique
.
If you can't use C++11 features, you can do the same with std::auto_ptr
:
std::auto_ptr<MyType> aScopePtr{ new MyType() };
Just be aware it's deprecated and has pitfalls.