You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

shared_ptr指向的Container对象的所有成员是否均存储在堆上?

问题解答

核心问题:shared_ptr指向的对象及其成员是否都存储在堆上?

先看给出的代码:

#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;

}

解答:

  1. shared_ptr指向的Container实例:通过std::make_shared<Container>创建的对象,完全存储在堆内存中。
  2. Container的成员m_elements:作为Container对象的一部分,它的本体(包括unordered_map的控制结构、桶数组指针等)属于堆上的Container实例,因此这部分也在堆上。
  3. unordered_map中的Element实例:std::unordered_map的元素存储是动态分配的,所有插入到m_elements中的Element对象,都会被容器分配到堆内存中。
  4. 关于shared_ptr本身:main函数中的container这个shared_ptr变量存储在栈上,但它管理的指针指向的是堆上的Container实例——这是两个不同概念:shared_ptr对象自身的存储位置取决于它的定义位置,而它指向的对象一定在堆上(当用make_shared创建时)。

总结:你提到的Container实例、它的成员m_elements的本体、以及m_elements中的所有Element实例,全部都存储在堆上。而shared_ptr自身的实例(main里的container变量)是在栈上的,但这不属于“shared_ptr指向的成员”范畴。

内容的提问来源于stack exchange,提问作者jcjuarez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 07:05:24