-
回首忆惘然
我defer在 CppCon 2014(YouTube 链接)上展示了 Go 风格的仅标头实现;我叫它Auto。恕我直言,就可教性、效率和绝对的万无一失而言,这仍然是最好的选择。在使用中,它看起来像这样:#include "auto.h"int main(int argc, char **argv){ Auto(std::cout << "Goodbye world" << std::endl); // defer a single statement... int x[4], *p = x; Auto( if (p != x) { // ...or a whole block's worth of control flow delete p; } ); if (argc > 4) { p = new int[argc]; }}实现如下所示:#pragma oncetemplate <class Lambda> class AtScopeExit { Lambda& m_lambda;public: AtScopeExit(Lambda& action) : m_lambda(action) {} ~AtScopeExit() { m_lambda(); }};#define Auto_INTERNAL2(lname, aname, ...) \ auto lname = [&]() { __VA_ARGS__; }; \ AtScopeExit<decltype(lname)> aname(lname);#define Auto_TOKENPASTE(x, y) Auto_ ## x ## y#define Auto_INTERNAL1(ctr, ...) \ Auto_INTERNAL2(Auto_TOKENPASTE(func_, ctr), \ Auto_TOKENPASTE(instance_, ctr), __VA_ARGS__)#define Auto(...) Auto_INTERNAL1(__COUNTER__, __VA_ARGS__)是的,这就是整个文件:只有 15 行代码!它需要 C++11 或更高版本,并且需要您的编译器支持__COUNTER__(尽管如果您需要可移植到某些不支持它的编译器,您可以将其__LINE__用作穷人的__COUNTER__)。至于效率,我从来没有见过 GCC 或 Clang 为Autoat-O2或更高级别的任何使用生成完美的代码——这是传说中的“零成本抽象”之一。原始源还有一个 C89 版本,它通过利用一些非常特定于 GCC 的属性在 GCC 上工作。
-
翻阅古今
与其他一些答案不同,此实现是零开销的,并且在语法上更好且更易于使用。它还具有零依赖性,从而减少了编译时间。您可以将此代码段粘贴到代码库中的任何位置,它就会正常工作。#ifndef deferstruct defer_dummy {};template <class F> struct deferrer { F f; ~deferrer() { f(); } };template <class F> deferrer<F> operator*(defer_dummy, F f) { return {f}; }#define DEFER_(LINE) zz_defer##LINE#define DEFER(LINE) DEFER_(LINE)#define defer auto DEFER(__LINE__) = defer_dummy{} *[&]()#endif // defer用法: defer { statements; };例子:#include <cstdint>#include <cstdio>#include <cstdlib>#ifndef deferstruct defer_dummy {};template <class F> struct deferrer { F f; ~deferrer() { f(); } };template <class F> deferrer<F> operator*(defer_dummy, F f) { return {f}; }#define DEFER_(LINE) zz_defer##LINE#define DEFER(LINE) DEFER_(LINE)#define defer auto DEFER(__LINE__) = defer_dummy{} *[&]()#endif // deferbool read_entire_file(char *filename, std::uint8_t *&data_out, std::size_t *size_out = nullptr) { if (!filename) return false; auto file = std::fopen(filename, "rb"); if (!file) return false; defer { std::fclose(file); }; // don't need to write an RAII file wrapper. if (std::fseek(file, 0, SEEK_END) != 0) return false; auto filesize = std::fpos_t{}; if (std::fgetpos(file, &filesize) != 0 || filesize < 0) return false; auto checked_filesize = static_cast<std::uintmax_t>(filesize); if (checked_filesize > SIZE_MAX) return false; auto usable_filesize = static_cast<std::size_t>(checked_filesize); // Even if allocation or read fails, this info is useful. if (size_out) *size_out = usable_filesize; auto memory_block = new std::uint8_t[usable_filesize]; data_out = memory_block; if (memory_block == nullptr) return false; std::rewind(file); if (std::fread(memory_block, 1, usable_filesize, file) != usable_filesize) return false; // Allocation succeeded, but read failed. return true;}int main(int argc, char **argv) { if (argc < 2) return -1; std::uint8_t *file_data = nullptr; std::size_t file_size = 0; auto read_success = read_entire_file(argv[1], file_data, &file_size); defer { delete[] file_data; }; // don't need to write an RAII string wrapper. if (read_success) { for (std::size_t i = 0; i < file_size; i += 1) std::printf("%c", static_cast<char>(file_data[i])); return 0; } else { return -1; }}PS:本地延迟对象以zz_和开头,而不是_这样它不会使调试器中的本地窗口混乱,而且因为用户标识符在技术上不应该以下划线开头。
-
温温酱
有一个提案std::unique_resource_t可以启用类似的代码auto file=make_unique_resource(::fopen(filename.c_str(),"w"),&::fclose);对于资源,它定义了一个通用的scope_exit,它应该与defer:// Always say goodbye before returning,auto goodbye = make_scope_exit([&out]() ->void{out << "Goodbye world..." << std::endl;});它将被考虑在 Post-C++17 标准中采用。