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

inserting object in a map without copying the object

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

#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!
}

编辑 我不是很清楚。该对象很大,所以我不想制作不必要的副本。但是我可以修改 class 的代码(也许我需要实现移动语义?)而不是用户代码(示例中的主要功能)。

使用安置语法:

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 ctor\n";}
  T &operator=(const T &other) = delete;
  T& operator=(T&& other) {x = other.x; std::cout << "move assigment\n";}
 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;
}