【问题标题】:Moving a shared_ptr to the method called on the object the shared_ptr points to将 shared_ptr 移动到 shared_ptr 指向的对象上调用的方法
【发布时间】:2017-06-27 07:23:00
【问题描述】:

给定

struct X {
    void f(std::shared_ptr<X>);
};
auto x(std::make_shared<X>());

我大概可以放心

x->f(std::move(x));

在 C++17 中,因为在构造 X::f 的参数之前评估了 x-&gt;f,对吧?据我所知,在早期版本的 C++ 中没有这样的保证。如何在 C++11 和 C++14 中实现类似的功能?

PS:请注意,即使使用std::unique_ptr 而不是std::shared_ptr,同样适用。

【问题讨论】:

  • 这也暗示了在离开同一个对象的成员函数的范围内/时销毁对象是否安全的问题。出于好奇:您为什么要这样做?

标签: c++ c++11 c++14 shared-ptr c++17


【解决方案1】:

我认为在 C++11 和 C++14 中不改变接口或使用任何晦涩的宏的最好方法是

auto & refX = *x;
refX.f(std::move(x));

【讨论】:

  • 严格来说,您只需要在取消引用 x 和对该对象调用 f 之间引入一个序列点。这提供了一个非常易读的解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-25
  • 2020-01-08
  • 2018-07-16
  • 1970-01-01
  • 1970-01-01
  • 2021-11-15
相关资源
最近更新 更多