如何在std :: unorderd_map中就地构造某个类的对象?

时间:2016-05-07 15:56:00

标签: c++ qt std unordered-map qgraphicsitem

我想在MyItem中存储多个来自Qt::QGraphicsItem 的对象std::unordered_map。据我了解,Qt::QGraphicsItem 是不可复制的:复制构造函数是私有的。

这很好;我不想复制MyItem。但我需要在原地构建MyItem。假设MyItem具有此构造函数签名:

MyItem::MyItem(int a, double b, std::string c);

这是我的std::unordered_map

std::unordered_map< KeyType, MyItem > myItemMap;

这一行有什么问题,KeyType可以在安置之前复制和构建:

myItemMap.emplace( correspondingKey, MyItem(3, 3.14, "hello") );

我收到此错误(剪切):

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

myItemMap.emplace(...)的论点必须如何?

2 个答案:

答案 0 :(得分:3)

您构建了Startup.cs public override async Task SignInAsync(ApplicationUser user, bool isPersistent, bool rememberBrowser) { var userIdentity = await CreateUserIdentityAsync(user).WithCurrentCulture(); // Clear any partial cookies from external or two factor partial sign ins AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie, DefaultAuthenticationTypes.TwoFactorCookie); if (rememberBrowser) { var rememberBrowserIdentity = AuthenticationManager.CreateTwoFactorRememberBrowserIdentity(ConvertIdToString(user.Id)); AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = isPersistent }, userIdentity, rememberBrowserIdentity); } else { //AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = isPersistent }, userIdentity); if (isPersistent) { AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = true }, userIdentity); } else { AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = true, ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(30) }, userIdentity); } } } 然后尝试复制的值。 MyItem函数的要点是将构造留给emplace。它变得复杂,因为您需要传递emplace,您希望推迟构建map

pair

请参阅http://en.cppreference.com/w/cpp/container/unordered_map/emplace

答案 1 :(得分:1)

如果将移动构造函数添加到MyItem

,则代码将起作用
MyItem(MyItem&& old)
    : Base(old.parentItem())
{
    for (QGraphicsItem* child : old.childItems()) {
        child->setParentItem(this);
    }
    old.setParentItem(nullptr);
}

然后实例将自动移动而不被复制。