RAII order of operation

D

dot

Let say we have a function:

class C
{
volatile A a;

public:
A f() const;
};

A C::f()
{
volatile scoped_mutex m;
return a;
}

Which of the following operations shall take place first:
* copy-construction of a
* destruction of m

Thanks,
Ben
 
A

Ali Karaali

Let say we have a function:

class A
{
public :
A(const A & r)
{ cout << "A::A(const A&)" <<endl; }

~A()
{ cout << "A::~A()" << endl; }
};
class C
{
    volatile A a;

public :
   
A f() const;
};

A C::f()
{
    volatile scoped_mutex m;
    return a;
}

Which of the following operations shall take place first:
   * copy-construction of a
   * destruction of m

Thanks,
Ben

You can find now...
 
M

Marcel Müller

Hi!
Let say we have a function:

class C
{
volatile A a;

public:
A f() const;
};

A C::f()
{
volatile scoped_mutex m;
return a;
}

Which of the following operations shall take place first:
* copy-construction of a
* destruction of m

None of them is ever called because your code won't compile for several
reasons. The most important one is that a copy constructor cannot be
invoked with a volatile object a. The implicit cast from volatile A to
const A& is not allowed.

If you remove all the volatile statements (which I would recommend) then
A's copy constructor is invoked before the destructor of m. However,
that may not help you because the compiler is allowed to invoke another
copy constructor on statements like

A a2 = c.f();

It is up to the compiler to eliminate the second call to A::A(const A&).


Marcel
 
P

peter koch

Let say we have a function:

class C
{
    volatile A a;

   public:
    A f() const;

};

A C::f()
{
    volatile scoped_mutex m;
    return a;

}

Which of the following operations shall take place first:
   * copy-construction of a
   * destruction of m

copy-construction of a. This is guaranteed by the standard, so no need
to test.

/Peter
 
P

peter koch

Let say we have a function:

class C
{
    volatile A a;

   public:
    A f() const;

};

A C::f()
{
    volatile scoped_mutex m;
    return a;

}

As Marcel Müller mentioned, there is no need for using volatile here -
neither for the mutex nor for a. And you also miss a const on the
definition of C::f.

/Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top