简体   繁体   English

C ++:为什么这个简单的Scope Guard有效?

[英]C++: why this simple Scope Guard works?

Every looked at scope guard so far has a guard boolean variable. 到目前为止,每个看过范围守卫都有一个保护布尔变量。 For example, see this discussion: The simplest and neatest c++11 ScopeGuard 例如,请参阅此讨论: 最简单,最新的c ++ 11 ScopeGuard

But a simple guard works (gcc 4.9, clang 3.6.0): 但是一个简单的守卫工作(gcc 4.9,clang 3.6.0):

template <class C>
struct finally_t : public C {
    finally_t(C&& c): C(c) {}
    ~finally_t() { (*this)(); }
};
template <class C>
static finally_t<C> finally_create(C&& c) {
    return std::forward<C>(c);
}
#define FINCAT_(a, b) a ## b
#define FINCAT(a, b) FINCAT_(a, b)
#define FINALLY(...) auto FINCAT(FINALY_, __LINE__) = \
    finally_create([=](){ __VA_ARGS__ })

int main() {
    int a = 1;
    FINALLY( std::cout << "hello" << a << std::endl ; );
    FINALLY( std::cout << "world" << a << std::endl ; );
    return 0;
}

Why no temporary copies destructed? 为什么没有临时副本被破坏? Is it dangerous to rely on this behavior? 依赖这种行为是危险的吗?

You're observing the effects of Copy Elision (or Move Elision, in this case). 您正在观察Copy Elision(或移动Elision,在本例中)的效果。 Copy Elision is not guaranteed / mandatory, but usually performed by major compilers even when compiling w/o optimizations. 复制Elision不是保证/强制性的,但通常由主要编译器执行,即使在编译w / o优化时也是如此。 Try gcc's -fno-elide-constructors to see it "break": http://melpon.org/wandbox/permlink/B73EuYYKGYFMnJtR 试试gcc的-fno-elide-constructors,看看它“破解”: http//melpon.org/wandbox/permlink/B73EuYYKGYFMnJtR

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM