Hi,
Maybe this is an simple question. How can I insure that the objects of
a class must be allocated in the heap?
First, I do not quite understand, why you would want to do something like
that.
As for how you could go about it, here is an idea: You can make the
constructors private. Now, that sounds silly as it prevents construction.
However, you can have a friend. This way, only the friend class is able to
construct objects. If that friend happens to only allocate objects via new,
then you are fine. E.g.:
#include <algorithm>
#include <iostream>
class handle;
class forbidden {
friend class handle;
int i;
forbidden ( int j = 0 )
: i ( j )
{
std::cout << "created\n";
}
~forbidden ( void ) {
std::cout << "destroyed\n";
}
forbidden ( forbidden const & other );
forbidden& operator= ( forbidden const & other );
public:
int get ( void ) const {
return ( i );
}
int set ( int j ) {
i = j;
return j;
}
}; // class forbidden
class handle {
forbidden* ptr;
public:
handle ( int i = 0 )
: ptr ( new forbidden ( i ) )
{}
handle ( handle const & other )
: ptr ( new forbidden ( other.get() ) )
{}
~handle ( void ) {
delete ptr;
}
handle & operator= ( handle const & other ) {
handle dummy ( other );
std::swap( this->ptr, dummy.ptr );
return ( *this );
}
int get ( void ) const {
return ( ptr->get() );
}
int set ( int i ) {
return( ptr->set(i) );
}
}; // handle
int main ( void ) {
handle x ( 5 );
std::cout << x.get() << '\n';
}
Note that this handle has value semantics. It is quite easy to implement
reference semantics instead.
If you just want to allow pointers to forbidden object but not forbidden
objects, you could do something like this:
#include <algorithm>
#include <iostream>
struct handle;
class forbidden {
friend class handle;
int i;
forbidden ( int j = 0 )
: i ( j )
{
std::cout << "created\n";
}
forbidden ( forbidden const & other );
forbidden& operator= ( forbidden const & other );
public:
int get ( void ) const {
return ( i );
}
int set ( int j ) {
i = j;
return j;
}
~forbidden ( void ) {
std::cout << "destroyed\n";
}
}; // class forbidden
struct handle {
static
forbidden* new_forbidden ( int i = 0 ) {
return( new forbidden ( i ) );
}
}; // handle
int main ( void ) {
forbidden* f_ptr = handle::new_forbidden ( 5 );
std::cout << f_ptr->get() << '\n';
delete f_ptr;
}
Anyway, it just seems like you want to make life harder for the clients of
your code. Generally, that is not a good idea: next week, someone will post
the question as to how your measures can be circumvented.
Best
Kai-Uwe Bux