[英]How can I in-place construct an object of some class in an std::unorderd_map?
I want to store a number of objects MyItem
, derived from Qt::QGraphicsItem
, in an std::unordered_map
. 我想将多个从Qt::QGraphicsItem
派生的对象MyItem
存储在std::unordered_map
。 As I understood, Qt::QGraphicsItem
is none-copyable : copy constructor is private. 据我了解, Qt::QGraphicsItem
是不可复制的:复制构造函数是私有的。
This is fine; 这可以; I don't want to copy MyItem
. 我不想复制MyItem
。 But I would need to construct MyItem
in-place. 但是我需要就地构建MyItem
。 Assuming MyItem
has this constructor signature: 假设MyItem
具有以下构造函数签名:
MyItem::MyItem(int a, double b, std::string c);
And this is my std::unordered_map
: 这是我的std::unordered_map
:
std::unordered_map< KeyType, MyItem > myItemMap;
What is wrong with this line, where KeyType
is copyable and constructed before the emplacement: 这行有什么问题,其中KeyType
是可复制的,并且在放置之前进行了构造:
myItemMap.emplace( correspondingKey, MyItem(3, 3.14, "hello") );
I get this error (cut): 我收到此错误(剪切):
use of deleted function 'MyItem::MyItem(const MyItem&)'
: first(std::forward<_U1>(__x)), second(__y) { }
^
'MyItem::MyItem(const MyItem&)' is implicitly deleted because the default definition would be ill-formed:
'QGraphicsItem::QGraphicsItem(const QGraphicsItem&)' is private
How does the arguments of myItemMap.emplace(...)
must look like? myItemMap.emplace(...)
的参数必须看起来如何?
You're constructing a MyItem
value which emplace
then tries to copy. 您正在构造一个MyItem
值,然后将其emplace
并尝试复制。 The point of the emplace
functions is to leave the construction to the map
. emplace
功能的重点是将结构留在map
。 It gets complicated because you need to pass a pair
, where you want to defer construction of second
. 这变得很复杂,因为您需要传递一pair
,而您要推迟second
pair
传递。
myItemMap.emplace(std::piecewise_construct,
std::forward_as_tuple(correspondingKey),
std::forward_as_tuple(3, 3.14, "hello"));
See http://en.cppreference.com/w/cpp/container/unordered_map/emplace . 请参阅http://en.cppreference.com/w/cpp/container/unordered_map/emplace 。
You code will work if you add a move constructor to MyItem
: 如果将移动构造函数添加到MyItem
则代码将起作用:
MyItem(MyItem&& old)
: Base(old.parentItem())
{
for (QGraphicsItem* child : old.childItems()) {
child->setParentItem(this);
}
old.setParentItem(nullptr);
}
Then the instance will be automatically moved and not copied. 然后,实例将被自动移动而不被复制。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.