Kai-Uwe Bux First, I do not quite understand, why you would want to do something likethat. As for how you could go about it, here is an idea: You can make theconstructors private. Now, that sounds silly as it prevents construction.However, you can have a friend. This way, only the friend class is able toconstruct 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 implementreference semantics instead. If you just want to allow pointers to forbidden object but not forbiddenobjects, 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 { staticforbidden* 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 ofyour code. Generally, that is not a good idea: next week, someone will postthe question as to how your measures can be circumvented.Best Kai-Uwe Bux 这篇关于我怎样才能确保必须在堆中分配类的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-10 11:38