Is it possible that I have a preliminary declaration of the class without making them a reference or pointer in the header file

// 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. // // ah #include "myclass.h" class a { public: a(); myclass me; }; 

I try to do it differently. However, I need to use dynamic allocation, which I usually try to avoid.

 // ah 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; } 

Can this be done without using any reference or pointer? (Or, more precisely, without using a new / delete)

+4
source share
3 answers

Not. The reason is because the compiler needs to know the size of your object (for example, myclass) in order to find out the size of the object (ie. Class β€œa” in your example). If you have only the previous declared class myclass, the compiler is not able to find out the size that should be allocated for class "a".

A link or pointer facilitates this b / c pointer or link has a certain size at compile time, and thus the compiler knows the memory requirements for class "a".

+7
source

You cannot avoid using a link or pointer. However, you can avoid the dynamic allocation of memory by including in class a array of bytes that is large enough to accommodate an instance of myclass , and use the "allocation new" to create this instance in this array (allocation new uses the new keyword, but it does not dynamically allocate memory).

0
source

As already mentioned, you cannot escape a link or a pointer. If your requirement is that you do not want to send "myclass.h" to your client, I suggest you use tr1 :: shared_ptr in your Hijra. You only need the forward declaration myclass in the header file. You have a β€œnew” object, but the β€œdeletion” will be done automatically using shared_ptr.

0
source

Source: https://habr.com/ru/post/1302442/


All Articles