1

是否可以unique_ptr通过在 lambda 中捕获它并延长 lambda 的寿命来延长 a 的寿命?

我试过了,但a=move(a)表达式出现语法错误。

#include <cstdio>
#include <functional>
#include <memory>
#include <iostream>

using namespace std;

struct A {
  A() { cout << "A()" << endl; }
 ~A() { cout << "~A()" << endl; }
};

int main() {
  std::function<void ()> f;
  {
    std::unique_ptr<A> a(new A());
    f = [a=move(a)] () mutable { return; };
  }
  return 0;
}
4

1 回答 1

1

那么你的代码的问题是std::function. 在您的示例中,它不是很友好,因为它需要它的可调用是可复制构造/可分配的,而您的 lambda 不是因为使用了仅移动类型unique_ptr

有许多示例可以为您提供移动友好的std::function.

我带着一个快速、hacky、可能容易出错但“在我的机器上工作”的版本来到这里:

#include <memory>
#include <iostream>
#include <type_traits>


struct A {
  A() { std::cout << "A()" << std::endl; }
 ~A() { std::cout << "~A()" << std::endl; }
};

template <typename Functor>
struct Holder
{
    static void call(char* sbo) {
        Functor* cb = reinterpret_cast<Functor*>(sbo);
        cb->operator()();
    }

    static void deleter(char* sbo) {
        auto impl = reinterpret_cast<Functor*>(sbo);
        impl->~Functor();
    }

};

template <typename Sign> struct Function;

template <>
struct Function<void()>
{
    Function() = default;
    ~Function() {
        deleter_(sbo_);
    }

    template <typename F>
    void operator=(F&& f)
    {
        using c = typename std::decay<F>::type;
        new (sbo_) c(std::forward<F>(f));
        call_fn_ = Holder<c>::call;
        deleter_ = Holder<c>::deleter;
    }

    void operator()() {
        call_fn_(sbo_);
    }

    typedef void(*call_ptr_fn)(char*);
    call_ptr_fn call_fn_;
    call_ptr_fn deleter_;
    char sbo_[256] = {0,};
};

int main() {
  Function<void()> f;
  {
      std::unique_ptr<A> a(new A());
      f = [a=move(a)] () mutable { return; };
  }
  std::cout << "Destructor should not be called before this" << std::endl;
  return 0;
}

自己尝试一下: http: //coliru.stacked-crooked.com/a/60e1be83753c0f3f

于 2017-08-18T07:45:41.467 回答