Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

c++ - Are locals destroyed before or after evaluation of a function return value?

I am thinking of making a class which represents ownership of a synchronization primitive, something like this:

class CCriticalSectionLock
{
public:
    CCriticalSectionLock( CCriticalSection &cs ) : cs( cs )
    { cs.Enter(); }
    ~CCriticalSectionLock()
    { cs.Leave(); }
private:
    CCriticalSection &cs;
};

This looks like a good way to be able to take ownership during a function and ensure ownership is released even if there are multiple exit points or exceptions. It does, however, raise some subtle issues about exactly when the compiler will have various things evaluated. Consider the following use:

int MyMethod( void )
{
    not_locked(); // do something not under lock

    CCriticalSectionLock myLock( someCriticalSection );

    locked(); // do something under lock

    return ...; // some expression
}

AFAIK, C++ lifetime rules would guarantee that not_locked() would be called before the lock is taken, and that locked() would be called while the lock is held.

However, what I am not so clear on is exactly when the expression being returned would be evaluated with respect to the point at which the lock destructor is called. Is it guaranteed that the expression will be evaluated before the destructor? I would think so but I'm not 100% sure, and if not it could lead to very subtle, intermittent, hard-to-find bugs!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If they weren't, that would be very problematic.

Indeed, consider the following code :

int function(){

    MyClass myObject;
    //stuff
    return 5 + myObject.getNumericalValue();
}

with getNumericalValue() a simple member function that returns an int based on computations on member variable. If the expression was evaluated after the destruction of myObject, you would have undefined behavior, and using locals would be impossible in return statement (which isn't the case).

In your case, the lock will be destroyed after the evaluation of the return statement.

To add some strictness to that, let me quote the standard (§3.7.3/3, emphasis mine) :

If a variable with automatic storage duration has initialization or a destructor with side effects, it shall not be destroyed before the end of its block, nor shall it be eliminated as an optimization even if it appears to be unused

The end of the block, for a function, is after the return statement.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...