如何在C++ 11 lambda中跟踪对象的生命周期?

Sta*_*tas 6 c++ lambda shared-ptr weak-ptr c++11

有时,我们对捕获对象状态的lambda的生命周期一无所知(例如,将其从对象返回,将其注册为回调而无需取消订阅等).如何确保lambda在调用时不会访问已经销毁的对象?

#include <iostream>
#include <memory>
#include <string>

class Foo {
public:
    Foo(const std::string& i_name) : name(i_name) {}

    std::function<void()> GetPrinter() {
        return [this]() {
            std::cout << name << std::endl;
        };
    }

    std::string name;
};

int main() {
    std::function<void()> f;

    {
        auto foo = std::make_shared<Foo>("OK");
        f = foo->GetPrinter();
    }

    auto foo = std::make_shared<Foo>("WRONG");

    f();

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这个程序只是巧合地打印出"错误"而不是"OK"(http://ideone.com/Srp7RC)(似乎它只是为第二个Foo对象重用了相同的内存).无论如何,这是一个错误的计划.Foo我们执行时,第一个对象已经死了f.

Sta*_*tas 13

延长对象的生命周期

Lambdas可以捕获共享指针this,因此当至少存在一个lambda时,对象不会死亡.

class Foo : public std::enable_shared_from_this<Foo> {
public:
    Foo(const std::string& i_name) : name(i_name) {}

    std::function<void()> GetPrinter() {
        std::shared_ptr<Foo> that = shared_from_this();

        return [that]() {
            std::cout << that->name << std::endl;
        };
    }

    std::string name;
};
Run Code Online (Sandbox Code Playgroud)

http://ideone.com/Ucm2p8

通常,这不是一个好的解决方案,因为对象生命周期在这里以非常隐式的方式扩展.这是在对象之间生成循环引用的非常简单的方法.

跟踪物体寿命

Lambdas可以跟踪捕获的对象生命周期,并仅在对象仍然存活时使用该对象.

class Foo : public std::enable_shared_from_this<Foo> {
public:
    Foo(const std::string& i_name) : name(i_name) {}

    std::function<void()> GetPrinter() {
        std::weak_ptr<Foo> weak_this = shared_from_this();

        return [weak_this]() {
            auto that = weak_this.lock();
            if (!that) {
                std::cout << "The object is already dead" << std::endl;
                return;
            }

            std::cout << that->name << std::endl;
        };
    }

    std::string name;
};
Run Code Online (Sandbox Code Playgroud)

http://ideone.com/Wi6O11

跟踪对象生存期而不使用共享指针

正如hvd 所说,我们不能总是确定一个对象是由哪个管理的shared_ptr.在这种情况下,我建议使用以下内容lifetime_tracker.它是自包含的,不会影响您管理对象生存期的方式.

struct lifetime_tracker
{
private:
    struct shared_state
    {
        std::uint32_t count : 31;
        std::uint32_t dead  : 1;
    };

public:
    struct monitor
    {
        monitor() : state(nullptr) {}

        monitor(shared_state *i_state) : state(i_state) {
            if (state)
                ++state->count;
        }

        monitor(const monitor& t) : state(t.state) {
            if (state)
                ++state->count;
        }

        monitor& operator=(monitor t) {
            std::swap(state, t.state);
            return *this;
        }

        ~monitor() {
            if (state) {
                --state->count;
                if (state->count == 0 && state->dead)
                    delete state;
            }
        }

        bool alive() const {
            return state && !state->dead;
        }

    private:
        shared_state *state;
    };

public:
    lifetime_tracker() : state(new shared_state()) {}
    lifetime_tracker(const lifetime_tracker&) : state(new shared_state()) {}
    lifetime_tracker& operator=(const lifetime_tracker& t) { return *this; }

    ~lifetime_tracker() {
        if (state->count == 0)
            delete state;
        else
            state->dead = 1;
    }

    monitor get_monitor() const {
        return monitor(state);
    }

private:
    shared_state *state;
};
Run Code Online (Sandbox Code Playgroud)

用法示例

class Foo {
public:
    Foo(const std::string& i_name) : name(i_name) {}

    std::function<void()> GetPrinter() {
        auto monitor = tracker.get_monitor();

        return [this, monitor]() {
            if (!monitor.alive()) {
                std::cout << "The object is already dead" << std::endl;
                return;
            }

            std::cout << this->name << std::endl;
        };
    }

private:
    lifetime_tracker tracker;

    std::string name;
};
Run Code Online (Sandbox Code Playgroud)


小智 5

当您可以确定对象由a管理时,Stas的答案很好shared_ptr,但这并不总是可行的.但是,你总能做的是跟踪对象的生命周期,并在lambda中添加一个断言.

void ignore(void *) { }

class Foo {
public:
    Foo(const std::string& i_name) : name(i_name) {}
    Foo(const Foo& other) : name(other.name) {}
    Foo(Foo&& other) : name(std::move(other.name)) {}
    Foo& operator=(Foo other) { swap(*this, other); return *this; }
    friend void swap(Foo& a, Foo& b) { using std::swap; swap(a.name, b.name); }

    std::function<void()> GetPrinter() {
        std::weak_ptr<void> monitor = this->monitor;

        return [=]() {
            assert (!monitor.expired());
            std::cout << name << std::endl;
        };
    }

    std::string name;

private:
    std::shared_ptr<void> monitor{this, ignore};
};
Run Code Online (Sandbox Code Playgroud)

在构造函数中,共享指针monitor未显式初始化,而是通过其初始化器设置为指向this,并且在指针的生存期到期后不执行任何操作.这个想法不是要shared_ptr对释放对象负责,这个想法只是让shared_ptr对象的生命周期传递信息.

在创建lambda之前,您可以构造一个weak_ptr跟踪关联的lambda shared_ptr.如果对象已被破坏,那么其monitor成员也必然已经被破坏,并且通过该expired()功能可以看到它.