Scope
How do you make objects declared within a function persist after the function exits?
Wrap it in a class (a shared context)
Make the function and object variable members of the same class so they share scope
Use the constructor to create the object and initialize its value in one shot
Smart pointer method
Create a smart pointer (
std::shared_ptr
orstd::unique_ptr
) outside the function scopePass the smart pointer into the function
Use either the
new
keyword orstd::make_shared()
/std::make_unique()
to allocate memory and assign the new object to the pointernew
can only be used with astd::unique_ptr
; with astd::shared_ptr
you must usestd::make_shared
The new object will persist after the function exits
Double pointer, dynamic memory method
Pass a double pointer into the function
Change the value the double pointer points to, which is itself a pointer (address) where the object created inside the function will be stored
No need to return anything from the function
static
keyword method
static
keyword methodDeclare the object in the function using the
static
keywordThis will make the object persist after the function exits, but it will only be available within the scope of the function (i.e. if the function runs again)
Last updated