0

我是 boost:asio 的新手。我需要将 shared_ptr 作为参数传递给处理函数。

例如

  1. boost::asio::post(std::bind(&::function_x, std::move(some_shared_ptr)));

使用 std::move(some_shared_ptr) 正确吗?或者我应该如下使用,

  1. boost::asio::post(std::bind(&::function_x, some_shared_ptr));

如果两者都是正确的,哪一个是可取的?

提前致谢

问候尚卡尔

4

1 回答 1

1

Bind 按值存储参数。

所以两者都是正确的,可能是等价的。如果在绑定之后不使用,将参数移动到绑定中可能会更有效some_argument

警告:高级用例

(如果你想跳过这个

不是你问的:如果function_x采用右值引用参数怎么办?

很高兴你问。你不能。但是,您仍然可以通过左值引用接收并从中移动。因为:

std::move不动

右值引用仅用于指示可能从参数中移出的参数,从而启用一些智能编译器优化和诊断。

所以,只要你知道你的绑定函数只执行一次(!!)那么从左值参数移动是安全的。

在共享指针的情况下,实际上有更多的余地,因为从共享指针移动实际上根本不会移动指向的元素。

所以,一个小练习证明了这一切:

住在科利鲁

#include <boost/asio.hpp>
#include <memory>
#include <iostream>

static void foo(std::shared_ptr<int>& move_me) {
    if (!move_me) {
        std::cout << "already moved!\n";
    } else {
        std::cout << "argument: " << *std::move(move_me) << "\n";
        move_me.reset();
    }
}

int main() {

    std::shared_ptr<int> arg      = std::make_shared<int>(42);
    std::weak_ptr<int>   observer = std::weak_ptr(arg);

    assert(observer.use_count() == 1);

    auto f = std::bind(foo, std::move(arg));

    assert(!arg);                      // moved
    assert(observer.use_count() == 1); // so still 1 usage

    {
        boost::asio::io_context ctx;
        post(ctx, f);
        ctx.run();
    }

    assert(observer.use_count() == 1); // so still 1 usage
    f(); // still has the shared arg

     // but now the last copy was moved from, so it's gone
    assert(observer.use_count() == 0); //
    f(); // already moved!
}

印刷

argument: 42
argument: 42
already moved!

何必?

你为什么要关心以上这些?好吧,因为在 Asio 中有很多处理程序可以保证精确执行一次,所以有时可以避免共享指针的开销(同步、控制块的分配、删除器的类型擦除)。

也就是说,您可以使用仅移动处理程序std::unique_ptr<>

住在科利鲁

#include <boost/asio.hpp>
#include <memory>
#include <iostream>

static void foo(std::unique_ptr<int>& move_me) {
    if (!move_me) {
        std::cout << "already moved!\n";
    } else {
        std::cout << "argument: " << *std::move(move_me) << "\n";
        move_me.reset();
    }
}

int main() {
    auto arg = std::make_unique<int>(42);
    auto f = std::bind(foo, std::move(arg)); // this handler is now move-only

    assert(!arg); // moved

    {
        boost::asio::io_context ctx;
        post(
            ctx,
            std::move(f)); // move-only, so move the entire bind (including arg)
        ctx.run();
    }

    f(); // already executed
}

印刷

argument: 42
already moved!

这将对使用大量组合操作的代码有很大帮助:您现在可以以零开销将操作的状态绑定到处理程序中,即使它更大并且动态分配。

于 2021-04-21T15:38:53.427 回答