c++:另一个简单的作用域保护
C++ : other one simple scope guard
让我们问一下这个简单的作用域保护:
template <class T>
struct finop_t {
T& t;
~finop_t() { t(); }
};
#define FINALLY__(l, cl)
auto FIN ## l ## clo = cl;
finop_t<decltype(FIN ## l ## clo)> FIN ## l ## fin { FIN ## l ## clo}
#define FINALLY_(l, cl) FINALLY__(l, cl)
#define FINALLY(...) FINALLY_(__LINE__, ([=](){__VA_ARGS__}))
int main() {
FINALLY( std::cout << "hello" << std::endl ; );
std::cout << "one" << std::endl;
FINALLY( std::cout << "world" << std::endl ; );
std::cout << "second" << std::endl;
return 0;
}
在这里依赖销毁顺序安全吗?即,它是安全的假设~finop_t()
将在lambda析构函数之前调用?
是的,它是安全的。宏将lambda存储在一个局部变量中。局部变量的销毁顺序是固定的(与构造顺序相反)。这样就保证了~finop_t()
析构函数在相应的lambda (FIN ## l ## clo
)析构函数之前被调用。
局部变量的销毁顺序与它们的构造顺序相反。
这里有一个更有效的方法,它不需要引用,并使用复制-省略来原地构造lambda。
(注意,您可能想要考虑[&]而不是[=],但这取决于您的判断)
#include <iostream>
template <class T>
struct finop_t {
finop_t(T&& t) : t(std::forward<T>(t)) {}
T t;
~finop_t() { t(); }
};
template<class F>
finop_t<F> make_finop_t(F&& f)
{
return finop_t<F>(std::forward<F>(f));
}
#define FINALLY__(l, cl)
auto FIN ## l ## fin = make_finop_t(cl);
#define FINALLY_(l, cl) FINALLY__(l, cl)
#define FINALLY(...) FINALLY_(__LINE__, ([=](){__VA_ARGS__}))
int main() {
FINALLY( std::cout << "hello" << std::endl ; );
std::cout << "one" << std::endl;
FINALLY( std::cout << "world" << std::endl ; );
std::cout << "second" << std::endl;
return 0;
}
相关文章:
- 未在作用域中声明unordered_map
- 有没有一种方法可以在编译时获得作用域类名
- C++quit()函数中可能存在作用域问题
- 未在此作用域OpenCV3.4中声明cvSaveImage
- 全局作用域中函数指针的赋值
- 在类函数中初始化外部作用域变量
- 不同作用域中的静态变量和全局变量
- 是同一作用域的函数部分中的函数调用
- 未在此作用域中声明的函数和变量 (C++)
- 类作用域的类型别名"using":[何时]方法中的用法可以先于类型别名?
- 将作用域枚举转换为基础类型
- 表达式必须具有完整或无作用域的枚举图
- 在构造函数中输入对象时C++类成员作用域
- 无法让"std::enable_if"适用于无作用域枚举
- 为什么不能直接引用作用域枚举类成员,而不能为无作用域枚举生成类成员?
- 函数未在作用域中声明 / 如何结合使用 header.h、header.cpp 和 main.cpp?
- 错误:表达式必须具有算术、无作用域枚举或带有运算符重载的指针类型
- 无法从派生类型的作用域访问另一个实例的受保护成员
- 类的静态成员变量(受保护)的作用域
- c++:另一个简单的作用域保护