在地图中插入对象而不复制对象

inserting object in a map without copying the object

本文关键字:对象 复制 插入 地图      更新时间:2023-10-16

如果对象的类禁用了复制构造函数并禁用了复制运算符,是否可以在映射中插入对象?移动语义在这里有用吗?

#include <map>
class T {
public:
  T(int v): x(v) {};
private:
  T(const T &other); // disabled!
  T &operator=(const T &other); // disabled!
  int x;
};
int main() {
  std::map<int, T> m;
  m[42] = T(24);  // compilation error here!
}

编辑我不完全清楚。这个物体很大,所以我不想做不必要的副本。但是我可以修改类的代码(也许我需要实现移动语义?)而不是用户代码(示例中的主函数)。

使用放置语法:

m.emplace(std::piecewise_construct,
          std::forward_as_tuple(42), std::forward_as_tuple(24));
//                              ^^                         ^^
//                            int(42)                     T(24)

或者,在 C++17 中,使用 try_emplace

m.try_emplace(42, 24);

这可能是您要查找的内容:

class T {
public:
  T(){};
  T(int v): x(v) {};
  T(const T &other) = delete;
  T(T&& other) {x = other.x; std::cout << "move ctorn";}
  T &operator=(const T &other) = delete;
  T& operator=(T&& other) {x = other.x; std::cout << "move assigmentn";}
 private:
  int x;
};
int main() {
  std::map<int, T> m;
  m.insert(std::make_pair(42, T(24))); 
  m[44] = T(25);
}

您可以插入为指针:

public:
    T(int v) : x(v) {};
    int getX(){ return this->x; }
private:
    T(const T &other); // disabled!
    T &operator=(const T &other); // disabled!
    int x;
};
int main() 
{
    std::map<int, T*> m;
    m[42] = new T(24);  // no compilation error here!
    std::cout << m[42]->getX() << std::endl; // prints out 24
    return 0;
}