在地图中插入对象而不复制对象
inserting object in a map without copying the object
如果对象的类禁用了复制构造函数并禁用了复制运算符,是否可以在映射中插入对象?移动语义在这里有用吗?
#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;
}
相关文章:
- 为什么C++在将一个对象复制到另一个对象时需要对这两个对象进行低级常量限定
- 如何在向量列表初始化时避免对象复制以及如何延长临时的生存期
- 了解在 C++ 中分配容器时的对象复制
- C++类对象复制构造函数和运算符=
- 复制 elision/RVO 会导致从同一对象复制/移动吗?
- 如何在循环内将大对象复制到omp任务中?
- 为什么当我添加一个不同的对象(复制构造函数中的参数)时调用复制构造函数?
- 无法将类构造函数中新创建的对象复制到 C++ 中的向量成员
- 将C++对象复制到指向新指针的指针处
- 将一个 OpenCV OutputArrayOfArrays 对象复制到另一个对象
- 选择性地禁用隐式对象复制
- 不能从文件到指针向量的对象复制
- 从派生对象复制构造
- OpenCV Mat对象复制速度更快
- 将子对象复制到父对象
- 为什么普通的 c++ 编译器不优化对象复制?
- C :将一个对象复制到构造函数中的另一个对象
- 使用命名对象复制构造函数
- 不必要的对象复制 - C++ STL
- 如何将一个类的对象复制到另一个类中