Object in Pimpl structure

K

keith

Hi, I'm having weird run-time errors and it's clearly something I'm
doing wrong, but I don't see what's going on.

Class B has a pointer to a structure containing a bunch of vars, and
an object of class A as shown in the code in the first example below.

Everything works fine when I take the A object out of the private
structure and put the object itself inside B as in the second example,
but when I do it as shown in the first example, 'bad stuff happens' -
looks a bit like heap corruption, but I haven't been able to pin it
down yet.

Any ideas or whacks with the clue-bat appreciated.

//--------------THIS VERSION FAILS!
// b.h----------------------------
struct BPrivate;
class B
{
private:
struct BPrivate* p_;

public:
B();
~B();
}

// b.cc----------------------------
#include "a.h"
#include "b.h"
struct BPrivate
{
int var1;
int var2;
A Aobject;
};

B::B() : p_(new BPrivate()) {} //<<should invoke A's default c-tor,
no?
B::~B() { delete p_; } // likewise, should call A's d-tor?

//--------------THIS VERSION WORKS!
// b.h----------------------------
struct BPrivate;
class B
{
private:
struct BPrivate* p_;
A Aobject;

public:
B();
~B();
}

// b.cc----------------------------
#include "a.h"
#include "b.h"
struct BPrivate
{
int var1;
int var2;
};

B::B() : p_(new BPrivate()), Aobject() {}
B::~B() { delete p_; }
 

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

A simpler Pimpl Idiom ? 6
Partial pimpl design pattern? 8
Pimpl Idiom 7
shared_ptr problems 0
pimpl optimization 7
auto_ptr and PIMPL 10
pimpl idiom and singletons 4
Object member with constructor parameter? 4

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,226
Members
46,815
Latest member
treekmostly22

Latest Threads

Top