Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning to a std::shared_ptr member variable

Tags:

c++

c++11

I have a class foo, with a member bar of type std::shared_ptr<int>:

class foo
{
    std::shared_ptr<int> bar;
    /*other stuff here*/
};

In that class I want to assign a new int to bar. But I can't write bar = new int(); as the pointer does not have a public assignment operator.

How should I do this? I could std::move or std::swap but neither of those seem right.

like image 641
P45 Imminent Avatar asked Sep 24 '15 09:09

P45 Imminent


People also ask

Can shared_ptr be Nullptr?

A null shared_ptr does serve the same purpose as a raw null pointer. It might indicate the non-availability of data. However, for the most part, there is no reason for a null shared_ptr to possess a control block or a managed nullptr .

Why is shared_ptr unique deprecated?

What is the technical problem with std::shared_ptr::unique() that is the reason for its deprecation in C++17? this function is deprecated as of C++17 because use_count is only an approximation in multi-threaded environment.

What is the purpose of the shared_ptr <> template?

std::shared_ptr. std::shared_ptr is a smart pointer that retains shared ownership of an object through a pointer. Several shared_ptr objects may own the same object.


1 Answers

bar = std::make_shared<int>(); is one way, especially if you like to retain the tractability of an assignment operator.

like image 130
Bathsheba Avatar answered Oct 12 '22 11:10

Bathsheba