引用自 zltoolkit
头文件onceToken.h
/*
* Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
*
* This file is part of ZLToolKit(https://github.com/xia-chu/ZLToolKit).
*
* Use of this source code is governed by MIT license that can be found in the
* LICENSE file in the root of the source tree. All contributing project authors
* may be found in the AUTHORS file in the root of the source tree.
*/
#ifndef UTIL_ONCETOKEN_H_
#define UTIL_ONCETOKEN_H_
#include <functional>
#include <type_traits>
using namespace std;
namespace toolkit {
class onceToken {
public:
typedef function<void(void)> task;
template<typename FUNC>
onceToken(const FUNC &onConstructed, function<void(void)> onDestructed = nullptr) {
onConstructed();
_onDestructed = std::move(onDestructed);
}
onceToken(nullptr_t, function<void(void)> onDestructed = nullptr) {
_onDestructed = std::move(onDestructed);
}
~onceToken() {
if (_onDestructed) {
_onDestructed();
}
}
private:
onceToken() = delete;
onceToken(const onceToken &) = delete;
onceToken(onceToken &&) = delete;
onceToken &operator=(const onceToken &) = delete;
onceToken &operator=(onceToken &&) = delete;
private:
task _onDestructed;
};
} /* namespace toolkit */
#endif /* UTIL_ONCETOKEN_H_ */
适用使用场景:在函数作用域结束后析构对应对象,或避免因抛异常时没有对象。
socket->setOnErr([weak_self, weak_session, id](const SockException &err) {
// 在本函数作用域结束时移除会话对象
// 目的是确保移除会话前执行其 onError 函数
// 同时避免其 onError 函数抛异常时没有移除会话对象
onceToken token(nullptr, [&]() {
// 移除掉会话
auto strong_self = weak_self.lock();
if (!strong_self) {
return;
}
assert(strong_self->_poller->isCurrentThread());
//从共享map中移除本session对象
lock_guard<std::recursive_mutex> lck(*strong_self->_session_mutex);
strong_self->_session_map->erase(id);
});
// 获取会话强应用
if (auto strong_session = weak_session.lock()) {
// 触发 onError 事件回调
strong_session->onError(err);
}
});