Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When an automatic variable get out of scope, in what order operations occurs? [duplicate]

Tags:

c++

Is the mutex used in method GetValues() released before or after copy constructing the dummy instance?

class Protect
{};

class Test
{
public:
    Protect GetValues() const;

private:
    Protect m_protVal;
    Mutex m_mutex;
};

Protect Test::GetValues() const
{
    CLockGuard lock(m_mutex);

    return m_protVal;
}

int main(int argc, char** argv)
{
    Test myTestInstance;

    Protect dummy = myTestInstance.GetValues();
}

Let's assume CLockGuard and Mutex are standard classes provided with boost lib.

like image 474
nabulke Avatar asked Nov 18 '22 23:11

nabulke


1 Answers

Yes:-). Formally, there are two “copies” when returning a value: one to some special place used to actually return the value, and the second after the return, to wherever the value must be finally placed. Either or both can be optimized out, however. The destruction of local variables occurs after the first, but before the second. (NRVO and RVO may lead to the first being optimized out, but they don't affect your code, since you're not returning a local variable.)

like image 96
James Kanze Avatar answered Dec 20 '22 12:12

James Kanze