Jump to content

C++ Language/Indirection/SmartPointers/SmartCompilerTemporary

From Wikibooks, open books for an open world

C++ creates a compiler-temporary for the new CRComplex(11,22) portion of std::unique_ptr<CRComplex> piVar(new CRComplex(11,22));. To guard against memory leaks from exceptions occuring before that compiler-temporary is given to the smart pointer, use std::make_unique<CRComplex>(11,22) in place of new CRComplex(11,22) (a std::make_unique<>() compiler-temporary is already a smart pointer as soon as it exists).

Additional information about smart compiler-temporaries (includes interactive examples)