How do you use a smart pointer?

How do you use a smart pointer?

A smart pointer is like a regular (typed) pointer, like “char*”, except when the pointer itself goes out of scope then what it points to is deleted as well. You can use it like you would a regular pointer, by using “->”, but not if you need an actual pointer to the data. For that, you can use “&*ptr”.

Can shared_ptr be moved?

Copying a shared_ptr involves copying its internal state object pointer and changing the reference count. Moving it only involves swapping pointers to the internal reference counter, and the owned object, so it’s faster.

How are smart pointers moved around in C + +?

Different smart pointers require different strategies: A std::unique_ptr can’t be passed by value because it can’t be copied, so it is usually moved around with the special function std::move from the Standard Library. This is move semantics in action:

When do you pass a smart pointer by value?

Let’s dig deeper. Pass smart pointers by value to lend their ownership to the function, that is when the function wants its own copy of the smart pointer in order to operate on it. Different smart pointers require different strategies:

How is a smart pointer used in a class template?

As shown in the example, a smart pointer is a class template that you declare on the stack, and initialize by using a raw pointer that points to a heap-allocated object. After the smart pointer is initialized, it owns the raw pointer. This means that the smart pointer is responsible for deleting the memory that the raw pointer specifies.

When to use a special case smart pointer?

Special-case smart pointer for use in conjunction with shared_ptr. A weak_ptr provides access to an object that is owned by one or more shared_ptr instances, but does not participate in reference counting. Use when you want to observe an object, but do not require it to remain alive.