简体   繁体   English

使用make_shared防止复制构造

[英]Prevent copy-construction with make_shared

I have a manager class that allow clients to add components through two methods: one with no argument that default-construct the component and another one that takes an rvalue (which should allow client to use a custom constructor of the component). 我有一个管理器类,该类允许客户端通过两种方法添加组件:一种不带参数的默认构造组件的方法,另一种采用rvalue的方法(应允许客户端使用组件的自定义构造函数)。

Here's the code I came up with: 这是我想出的代码:

template <class TComponent>
std::shared_ptr<TComponent> AddComponent()
{
    return AddComponent(TComponent{ this });
}

template <class TComponent>
std::shared_ptr<TComponent> AddComponent(const TComponent &&obj)
{
    auto ptr = std::make_shared<TComponent>(obj);
    vec.push_back(ptr);
    return ptr;
}

The problem I have is that std::make_shared always copy-constructs the object. 我的问题是std :: make_shared总是复制构造对象。 Is there a way to prevent this behavior? 有没有办法防止这种行为? I read about perfect forwarding but it doesn't seem to help here. 我读到了关于完美转发的信息,但这似乎无济于事。

I read about perfect forwarding but it doesn't seem to help here. 我读到了关于完美转发的信息,但这似乎无济于事。

I don't see why it wouldn't. 我不明白为什么不会。

Simply remove the const to make move construction possible, and add std::forward : 只需删除const以使移动构造成为可能,然后添加std::forward

template <class TComponent>
std::shared_ptr<TComponent> AddComponent(TComponent &&obj)
{
    auto ptr = std::make_shared<TComponent>(std::forward<TComponent>(obj));
    vec.push_back(ptr);
    return ptr;
}

Now, rvalues will be moved. 现在,右值将被移动。 Lvalues will be copied which you cannot avoid. 左值将被复制,您将无法避免。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM