Reputation: 401
To create object on heap only-> 1>is there anything wrong in the code
class B
{
~B(){}
public:
void Destroy()
{
delete this;
}
};
int main() {
B* b = new B();
b->Destroy();
return 0;
}
why you cant create object of class b on stack 2>
class B
{
B(){}
public:
static B* Create()
{
return new B();
}
};
int main() {
//B S;
B* b = B::Create();
return 0;
}
3>how to create object only on stack and not on heap
Upvotes: 1
Views: 2625
Reputation: 1976
Look at Concrete Data Type idiom: To control object's scope and lifetime by allowing or disallowing dynamic allocation using the free store (heap)
Upvotes: 0
Reputation: 785
If you want to create object only in Heap make destructor as private. Once the destructor is made Private, the code will give compiler error in case on object creation on stack. If you do not use new the object will be created on stack.
1) Object creation only on Heap
class B
{
~B(){}
public:
void Destroy()
{
delete this;
}
};
int main() {
B* b = new B();
b->Destroy();
return 0;
}
Nothing seems to be wrong with above code, If you try to create the object on stack B b1
it will give compiler error.
2) For restricting the object creation on heap, Make operator new as private.
You code
class B
{
B(){}
public:
static B* Create()
{
return new B();
}
};
int main() {
//B S;
B* b = B::Create();
return 0;
}
This code is still creating object on Heap/Free store as it is using new.
3) To create object only on stack not on heap, the use of new operator should be restricted. This can be achieved making operator new as private.
class B
{
Private:
void *operator new(size_t);
void *operator new[](size_t);
};
int main() {
B b1; // OK
B* b1 = new B() ; // Will give error.
return 0;
}
Upvotes: 7