简体   繁体   English

C ++如何在不调用构造函数的情况下分配对象

[英]C++ How to assign object without calling constructor

I have a class: 我有一节课:

class C {
public:
    C(): _a(a++){}
private:
    static int a;
    int _a;
};

int C::a = 0;
C c = C(); // c._a is 0
C d = C(); // d._a is 1
C e = C(); // e._a is 2

This works out as I'd expect: a and obj._a increment by 1. But if I assign c, d, and e to an unordered_map, they increment by 2: 这符合我的预期:a和obj._a递增1.但是如果我将c,d和e分配给unordered_map,它们会递增2:

unordered_map<int, C> map;
C c = C(); // c._a is 0
map[0] = c;
C d = C(); // d._a is 2
map[1] = d;
C e = C(); // e._a is 4
map[2] = e;

How can I assign c, d, and e to map and still make the static int a increment by 1? 如何将c,d和e分配给map并仍使static int增加1?

The problem comes from your map. 问题来自你的地图。 When you access map[0], the map will look for the entry 0 and if it does not exists, will instantiate it and returns to you a reference to the new instance. 当您访问map [0]时,映射将查找条目0,如果它不存在,将实例化它并返回对新实例的引用。 Try using map.emplace(0, c) instead to add an item in your map. 尝试使用map.emplace(0, c)代替在地图中添加项目。

Your problem is that the expression map[0] is creating a default constructed 'C' (and incrementing the counter), and then that object is assigned to. 你的问题是表达式map[0]正在创建一个默认构造的'C'(并递增计数器),然后分配该对象。

The solution is to directly insert the object in the map with: 解决方案是直接在地图中插入对象:

    map.insert({0,c});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM