c++ - 将(临时?) std::string 传递给使用它来构造获取副本的对象的函数的最佳方法是什么?
问题描述
解决方案
您标记了 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)}; }
推荐阅读
- amazon-web-services - 编写火花数据帧或编写胶水动态帧,AWS Glue 中哪个选项更好?
- permissions - 表关系的 Hasura SELECT 权限
- php - 如何在 BDD 中以欧洲格式插入日期时间
- vuejs2 - v-dialog/v-overlay 上的 Vue @keydown 停止工作时
存在 - javascript - 异步/等待实现
- netlogo - 文件删除词(“链接” sim “.txt”)
- java - 产品和测试的不同自动配置?
- azure - 获取 Azure Data Lake Gen2 (ACL) 的特定用户权限
- java - 使用 Jsoup 获取嵌套在类中的类的 src
- javascript - 图像、文本和按钮对齐方式不得根据窗口大小而改变