【问题标题】:Where does the memory allocation happens for an underlying object of a static shared_ptr?静态 shared_ptr 的底层对象的内存分配发生在哪里?
【发布时间】:2017-11-29 19:29:47
【问题描述】:

我在 GENIVI/capicxx-core-runtime 中遇到了一个名为 Runtime 的类。下面指定的部分代码。

class Runtime {
 public:
     COMMONAPI_EXPORT static std::shared_ptr<Runtime> get();
     COMMONAPI_EXPORT Runtime();
     COMMONAPI_EXPORT virtual ~Runtime()

 private:
     static std::shared_ptr<Runtime> theRuntime__;
};

std::shared_ptr<Runtime> Runtime::theRuntime__ = std::make_shared<Runtime>();

std::shared_ptr<Runtime> Runtime::get() {
   return theRuntime__;
}

我怀疑theRuntime__ 变量。由于shared_ptr进行堆分配,那么theRuntime__变量的底层对象在这种情况下是分配在堆上还是分配在BSS/DATA段中?

【问题讨论】:

  • 如果“底层对象”是指theRuntime__ 指向的Runtime 实例,那么它是由std::make_shared&lt;Runtime&gt;() 调用在堆上分配的。
  • shared_ptr 指向的对象的内存取自堆,但theRuntime__ 对象的内存分配到 BSS 段 - 这是静态对象。

标签: c++ c++11 static shared-ptr


【解决方案1】:

theRuntime__ 管理的分配(仅供参考:您不能使用带有双下划线的标识符;它们是为实现而保留的)由std::make_shared 创建。这将动态分配内存,无论在哪里调用。

theRuntime__ 对象的存储本身是静态存储。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-19
    • 2011-12-21
    • 2012-06-11
    • 1970-01-01
    • 2020-06-18
    • 1970-01-01
    • 2016-02-03
    • 1970-01-01
    相关资源
    最近更新 更多