我试图利用类构造函数和解构函数通过RAII惯用语来表示和格式化我的日志文件中的作用域。使用单个import weakref
class One:
def __init__(self, two):
self.var1 = 1
self.two = weakref.ref(two)
def change(self):
self.two().var2 = 5
class Two:
def __init__(self):
self.one = One(self)
self.var2 = 2
self.one.change()
two = Two()
print(two.var2)
,打印" {"并增加全局缩进级别,以便在该缩进级别打印下一个记录的行。
#define
应打印"}"并在LogScopeRAII
结束时超出范围时自然地降低全局缩进级别。但是,我看到的行为是LogScopeRAII在构建后立即被解构。
假设:我认为问题在于LogScopeRAII是在作业的RHS上创建的(因此也是匿名的?)并且在行尾被销毁,但是我在'我不知道该怎么办。我认为Foo()
LOG_ANONYMOUS_VARIABLE
中的VSCOPE_F
会完成这个伎俩并导致它留下来,但它不是。
问题:在调用函数超出范围之前,如何阻止LogScopeRAII被解构?
/* Header */
LogScopeRAII::LogScopeRAII(Verbosity verbosity, const char* file, unsigned line, const char* format, ...)
{
// ...
// print "{" and then increase an indentation global var
}
LogScopeRAII::~LogScopeRAII()
{
// ...
// print "}" and then decrease the indentation global var
}
#define LOG_ANOMYMOUS_VARIABLE(str) LOG_CONCAT(str, __LINE__)
#define VSCOPE_F(verbosity, ...) \
LogScopeRAII LOG_ANONYMOUS_VARIABLE(raii) = \
((verbosity) > verb_cutoff() ? LogScopeRAII() : LogScopeRAII{verbosity, __FILE__, __LINE__, __VA_ARGS__}
#define SCOPE_F(verbosity_name, ...) VSCOPE_F(Verbosity_ ## verbosity_name, __VA_ARGS__)
#define SCOPE_FUNCTION(INFO) SCOPE_F(verbosity_name, __FUNCTION__)
/* Implementation */
void Foo()
{
SCOPE_FUNCTION(INFO) // print "{" and increase indentation
for (size_t i = 0; i < 3; ++i)
{
// do work
LOG(INFO, "Work logged");
}
// print "}" and decrease indentation
}
期望的输出:
{ Foo()
"Work Logged" // Note indentation
} 0.23 s: Foo()
编辑:将问题缩小
关键在于:三元似乎无法发挥作用。
这有效:
LogScopeRAII a(LogScopeRAII{ Verbosity_INFO, __FILE__, static_cast<unsigned>(__LINE__), "" });
但这不是:
LogScopeRAII a(((Verbosity_INFO) > indent) ? LogScopeRAII() : LogScopeRAII{ Verbosity_INFO, __FILE__, static_cast<unsigned>(__LINE__), "" });
我明白了:
{
}
Work logged
Work logged
Work logged
}
constructCounter: 1
destructCounter: 2
Exiting...
答案 0 :(得分:1)
#define VSCOPE_F(verbosity, ...) \
LogScopeRAII LOG_ANONYMOUS_VARIABLE(raii) = \
((verbosity) > verb_cutoff() ? LogScopeRAII() : LogScopeRAII{verbosity, __FILE__, __LINE__, __VA_ARGS__}
应该是
#define VSCOPE_F(verbosity, ...) \
LogScopeRAII LOG_ANONYMOUS_VARIABLE(raii) \
(((verbosity) > verb_cutoff() ? LogScopeRAII() : LogScopeRAII{verbosity, __FILE__, __LINE__, __VA_ARGS__})
否则你使用临时变量的复制构造函数。
(您也可以修复move-constructor和析构函数以允许当前的MACRO)