Ctor initialization problem with shared_ptr (boost)

B

bourez

class B;
typedef boost::shared_ptr<B> BPtr;

class A
{
public:
explicit A(BPtr b) : _b1(b) {}
A(BPtr b1, BPtr b2) : _b1(b1), _b2(b2) {}

void f() {
if (_b1) {
// do some stuff with _b1
}
if (_b2) {
// do some stuff with _b2
}
}
private:
BPtr _b1;
BPtr _b2;
};

I'd like to construct an object A using the second c-tor but with _b1
and _b2 sharing the same object. To achieve that, I write

BPtr b(new B);
A a(b, b);

Now, I'd like to do the initialization from a derived class D.

class D
{
public:
D() : A(?, ?) {}
};

Is there a way to achieve this without modifying the semantic of the
base class A ?

Thank you.
 
I

Ivan Vecerina

: class B;
: typedef boost::shared_ptr<B> BPtr;
:
: class A
: {
: public:
: explicit A(BPtr b) : _b1(b) {}
: A(BPtr b1, BPtr b2) : _b1(b1), _b2(b2) {}
:
: void f() {
: if (_b1) {
: // do some stuff with _b1
: }
: if (_b2) {
: // do some stuff with _b2
: }
: }
: private:
: BPtr _b1;
: BPtr _b2;
: };
:
: I'd like to construct an object A using the second c-tor but with _b1
: and _b2 sharing the same object. To achieve that, I write
:
: BPtr b(new B);
: A a(b, b);
:
: Now, I'd like to do the initialization from a derived class D.
:
: class D
: {
: public:
: D() : A(?, ?) {}
: };
:
: Is there a way to achieve this without modifying the semantic of the
: base class A ?

Possibly with an intermediate function.
Something like:

inline A makeADoubleB(BPtr b) { return A(b,b); }

class D
{
public:
D() : A(makeADoubleB(new B)) {}
};


I hope this helps,
Ivan
 
B

bourez

Hi Ivan,

Thank you :). I did not think to pass through the copy c-tor of the
base class.

Finally, I found also another solution: Passing through an
intermediate class between A and D, as follows:

class C: public A
{
protected:
C(BPtr _b) : A(_b, _b) {}
};

class D : public C
{
public:
D() : C(boost::shared_ptr<B>(new B)) {}
};

This avoids using copy c-tor, which could be impossible (when A non
copyable)

Christophe
 

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

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,071
Latest member
MetabolicSolutionsKeto

Latest Threads

Top