何时在堆与堆栈中创建对象?

时间:2014-09-11 04:15:13

标签: c++ stdmap

看一下这段代码:

class Profiler{
    const std::string id;
public:
    Profiler(const std::string id);
    Profiler(const Profiler &t);
//...
}

然后在代码的某处:

std::map<const std::string, Profiler> profilers;

以及其他地方我将容器填充为:

profilers.insert(std::pair<const std::string, Profiler>(id, Profiler(id)));

上述行总共调用了constructorcopy constructor 3次。一个用于创建临时Profiler,一个用于创建pair,另一个用于创建insert权限? profilers[id] = Profiler(id);也有相同数量的调用。

  1. 有什么方法可以减少这个数字吗?
  2. 正确地更改签名并不便宜(无论如何) 在堆中创建Profiler并将其地址存储在堆中 map? (Profiler对象很小)
  3. 感谢

1 个答案:

答案 0 :(得分:0)

我的情况,就像我的其他情况一样,stack更为可取。 为什么? 阅读比一个更好:

  1. why memory allocation on heap is much slower than onstack
  2. which is faster stack allocation or heap allocation
相关问题