Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are all members of a Smart Pointer allocated on the Heap?

Given the following code:

#include <unordered_map>
#include <memory>
#include <string>

class Element {

    public:
        Element(const std::string& value) {
            m_value = value;
        }
     
    private:
        std::string m_value;

};

class Container {

    public:
        Container(const std::string& value) {
            m_elements.emplace(std::make_pair("New Key",Element(value)));
        }

    private:
        std::unordered_map<std::string, Element> m_elements;

};

int main() {

    std::string str {"New Value"};
    auto container = std::make_shared<Container>(str);

    return 0;

}

Will all members of the Container shared_ptr instance be stored on Heap, including all instances of the Element class inside the m_elements unordered_map? My question comes down to: Are all members of a shared_ptr stored on the Heap?

like image 848
jcjuarez Avatar asked Oct 26 '25 08:10

jcjuarez


1 Answers

Are all members of a Smart Pointer allocated on the Heap?

If an object has dynamic storage duration, then by definition, that object is not a member object. All data members are stored within the memory of the enclosing object.

A smart pointer is a stateful object, and in practice, it needs at least one subject to represent that state. It could be a direct data member, or a data member of a base class.

std::make_shared<Container> crates an instance of Container with dynamic storage duration, and returns a shared pointer that owns the instance.

like image 74
eerorika Avatar answered Oct 29 '25 08:10

eerorika



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!