Google interview questions:
Objects that can only be created on the stack,CodeAs follows:ClassHeaponly
{
Public:
VoidDestroy ()Const
{
DeleteThis;
}
Private:
~Heaponly (){};
};
Int Main ()
{
// Heaponly OBJ;
Heaponly * Pobj = New Heaponly;
// Do things
Pobj -> Destroy ();
// Delete pobj;
Return 0 ;
}
Why do we need to provide the destory function?
First, we set the destructor to private so that the objects created on the stack cannot be destroyed automatically, resulting in a compilation error.
Then, we "force" users to create objects on heap only by using the new operator. However, another problem occurs. You cannot explicitly Delete the object you created, because delete calls the Destructor locally. Therefore, you must provide the destroy function destory similar to "delete" to delete objects in the function.
someone provides the following method to create objects on the stack, the difference is that he makes Article On constructors and new operators, as follows: class heaponly
{< br> Public :
static heaponly * Create ()
{< br> return New heaponly ();
}
Private:
Heaponly (){};
};
IntMain ()
{
//Heaponly OBJ;
Heaponly*Pobj=Heaponly: Create ();
Return0;
}
The constructor is private, so that you cannot create objects, whether you create them directly or create new ones. So he provides the static member function create ()
To create an object, and create an object in the heap through new. This method specifies that you must use the create function to create a class. It seems to be a design pattern. However, this method does not fully meet the question requirements. The question is that an error is reported when an object compiler is directly created, but the new method can be created.
Only create objects on the stack:
Class Onlystack
{
Public :
Onlystack (){}
Private :
Void * Operator New (Size_t );
Void Operator Delete ( Void * PTR );
//
}
Int Main ( Int Argc, Char * Argv [])
{
Onlystack OBJ; // OK
// Onlystack * pobj = new onlystack; // Error
}