Saturday, October 12, 2013

RAII object in constructor

Newsgroup: comp.lang.c++

Subject: RAII object in constructor

From: =?ISO-8859-1?Q?Marcel_M=FCller?= <news.5.maazl@...>

Date: Wed, 09 Oct 2013 22:48:50 +0200



I have a mutex lock that is implemented as RAII. I need to acquire the

mutex as long as the constructor runs. But for the /entire/ constructor

run not just the construction of the derived class.





Example:



#include <stdio.h>



// some mutex class

class Mutex

{

public:

// hold the Mutex (RAII)

struct Lock

{ Lock(Mutex& mtx)

{ puts("Lock()\n");

//...

}

~Lock()

{ puts("~Lock()\n");

//...

}

};

//...

};



// set of configuration parameters

struct Parameters

{ //...

};



class WorkerBase

{ //...

protected:

WorkerBase(const Parameters& params)

{ // do something with params...

}

};



class Worker : public WorkerBase

{

private:

static Parameters GlobalParams;

static Mutex ParamMtx; // protect the above



public:

// synchronized public access to the parameters

struct AccessParams : Mutex::Lock

{ AccessParams() : Mutex::Lock(ParamMtx) {}

operator Parameters&() { return GlobalParams; }

};



Worker() : WorkerBase(AccessParams())

{ AccessParams params; // !!! Mutex acquired twice!

// do something with params...

}

};



Parameters Worker::GlobalParams;

Mutex Worker::ParamMtx;



int main()

{ Worker worker;

// do something with worker...

}





As expected the mutex is acquired twice. But this is bad, since the idea

is to sample a consistent set of parameters and not to use one parameter

set for the base class and some other one for the derived class.



Any ideas how to solve this?





Marcel







via Usenet Forums - Usenet Search,Free Usenet - comp.lang.c++ http://www.pocketbinaries.com/usenet-forums/showthread.php?104289-RAII-object-in-constructor&goto=newpost

View all the progranning help forums at:

http://www.pocketbinaries.com/usenet-forums/forumdisplay.php?128-Coding-forums

No comments:

Post a Comment