tags:

views:

70

answers:

3
// I prefer to perform forward declaration on myclass, as I do not
// wish to ship "myclass.h" to client
// However, the following code doesn't allow me to do so, as class defination
// is needed in header file.
//
// a.h
#include "myclass.h"
class a {
public:
    a();
    myclass me;
};

I try to do it another way around. However, I need to use dynamic allocation, which I usually try to avoid.

// a.h
class myclass;
class a {
public:
    a();
    myclass& me;
};

// But I just wish to avoid new and delete, is it possible?
// a.cpp
#include "myclass.h"

a::a() : me(*(new myclass())) {
}

a::~a() {
    delete *myclass;
}

Is it possible to do so, without using any reference or pointer? (Or more precisely, without using new/delete)

+6  A: 

No. The reason being, that the compiler needs to know the size of your object (i.e. myclass) in order to know the size of the object (i.e. class "a" in your example). If you have only forward declared myclass, the compiler has no way of knowing the size that must be allocated for the "a" class.

A reference or pointer alleviates this b/c a pointer or reference has a defined size at the time of compilation and thus the compiler knows the memory requirements for class "a".

RC
A: 

You can't avoid using a reference or pointer. You can, however, avoid allocating memory dynamically -- by including in class a an array of bytes that's large enough to house the myclass instance, and using "placement new" to construct that instance in that array (placement new does use the keyword new, but it does not dynamically allocate memory).

Alex Martelli
While this certainly is doable, it introduces risks: what if myclass changes and gets bigger, and you forget to increase your compile-time constant of class a's size?
Philip Potter
@Philip, obviously what you do to ward such dangers is, you add the appropriate assert in the .cpp file so that the compile will let you know in no uncertain terms if the `sizeof` the `class a` instance is `>` the buffer's size -- surely not a difficult or strange thing to do. Therefore I disagree that it "introduces risks".
Alex Martelli
A: 

As others have mentioned, you cannot avoid a reference or pointer. If your requirement is that you don't want to ship the "myclass.h" to your client, I suggest you use a tr1::shared_ptr in your "a.h". You only need the forward declaration of myclass in you header file. You do have to "new" the object, but the "delete" will be done automatically by the shared_ptr.

Ralph