【问题标题】:What should be preferred, moving or forwarding arguments什么应该是首选,移动或转发参数
【发布时间】:2022-01-14 15:00:01
【问题描述】:

下面是模板化List 的简化示例,其中两个append_move() 和append_forward() 函数具有相同的目标,获取参数并将它们放入容器List。第一个append_move() 函数采用按值传递的arg1,然后将其移至emplace_back() 函数。第二个append_move()函数使用arg1的自动推演,然后转发给emplace_back()函数。

append_forward() 函数比append_move() 函数有什么优势吗?应该首选哪个函数?

#include <deque>
#include <string>
#include <utility>

template<typename T>
class List
{
    public:
        void append_move(T arg1, std::string arg2)
        {
            list.emplace_back(std::move(arg1), std::move(arg2));
        }

        template<typename X>
        void append_forward(X&& arg1, std::string arg2)
        {
            list.emplace_back(std::forward<X>(arg1), std::move(arg2));
        }

    private:
        std::deque<std::pair<T, std::string>> list;
};

【问题讨论】:

  • 考虑当你实例化像List&lt;int &amp;&gt; 这样的东西时会发生什么。你想允许还是禁止?
  • append move 会在调用时复制 arg1,append_forward 不会
  • @ChrisDodd Will not work 也不允许引用集合。 (除非你愿意做一些模板专业化并开始使用 std::reference_wrapper)
  • @PepijnKramer:这取决于容器——可以实现它们以直接支持引用。这就是为什么我问你是允许还是禁止这样做。
  • @Kam 如果T 恰好有任何显式的单参数构造函数,那么从语义的角度来看,这两者甚至都不是等价的。

标签: c++ move template-argument-deduction


【解决方案1】:

前进或移动

如果T 的析构函数无法优化并产生可见的副作用,例如

struct Loud { ~Loud() { std::cout << "destructor\n"; } };

然后

List<Loud> list;
Loud const loud;
list.append_forward(loud);

调用的析构函数少于

list.append_move(loud);

因为后者再构造一个对象 => 必须再调用一个析构函数。所以,转发更可取。

但是,它使 API 不那么漂亮:

another_list.append_move({"some", "arguments"}); // works and pretty
//another_list.append_forward({"some", "arguments"}); // doesn't compile
another_list.append_forward(Foo{"some", "arguments"}); // works

手动重载

因此,不幸的是,提供手写重载似乎是这三个中最好的解决方案(对于您的代码的用户):

void append_overload(T&& t); // TODO actually implement
void append_overload(T const& t) { append_overload(T{t}); }

安放

但是(再一次),如果您关心所有这些,请考虑安置:

template<typename... As> void append_emplace(As&&... args) {
  list.emplace_back(std::forward<As>(args)...);
}
// works and pretty as long as you don't need to pass-construct two arguments
another_list.append_emplace("some", "arguments");

其他重载

此外,如果您有更多 append_* 重载,请注意转发/放置版本的优先级较低,因为它们是模板。选择权在你。

【讨论】:

  • 感谢您详尽的回答。我有两个问题。 1)当您谈到少一个析构函数时,您是指append_move()函数的参数arg1中传递的对象副本的析构函数吗? 2) 我对您使用带有一个参数的another_list.append_move() 和another_list.append_move() 函数有点困惑,因为在我的示例中,我使用的是带有两个参数的函数。只是为了方便解释吗?
  • @Kam 1) 是的;顺便说一句,在这种情况下,append_forward 会得到一个const&amp;,从而避免创建(=> 破坏)不需要的对象。 2) 是的;顺便说一句,在您的情况下实施/使用 append_emplace 可能会令人不快(有两个参数)。
猜你喜欢
  • 2020-08-21
  • 2020-10-29
  • 1970-01-01
  • 2012-10-31
  • 1970-01-01
  • 2017-01-17
  • 2010-09-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多