首页 > 解决方案 > 将(临时?) std::string 传递给使用它来构造获取副本的对象的函数的最佳方法是什么?

问题描述

标签: c++c++17move-semanticsstdstring

解决方案


您标记了 C++17,因此您可以使用移动语义(来自 C++11)并在main().

在我看来,收到副本的签名是可以的。

但是你必须在std::move()里面使用f()

Foo * f (std::string s)
 { return new Foo{std::move(s)}; }
// ...............^^^^^^^^^

Foo()构造函数内部

Foo (std::string s_) : s{std::move(s_)} { }
// ......................^^^^^^^^^

或制作不必要的副本。

另一种方法是使用模板类型、通用引用和std::forward.

我是说

struct Foo
 {
   std::string s;

   template <typename S>
   Foo (S && s_) : s{std::forward<std::string>(s_)} { }
 };

template <typename S>
Foo * f (S && s)
 { return new Foo{std::forward<S>(s)}; }

推荐阅读