Private Destructor

轉載自 http://www.geeksforgeeks.org/private-destructor/

Private Destructor

Predict the output of following programs.

复制代码
#include <iostream>
using namespace std;
 
class Test
{
private:
   ~Test() {}
};
int main()
{ }
复制代码

The above program compiles and runs fine. It is not compiler error to create private destructors. What do you say about below program.

复制代码
#include <iostream>
using namespace std;
 
class Test
{
private:
   ~Test() {}
};
int main()
{ 
  Test t; 
}
复制代码

The above program fails in compilation. The compiler notices that the local variable ‘t’ cannot be destructed because the destructor is private. What about the below program?

复制代码
#include <iostream>
using namespace std;
 
class Test
{
private:
   ~Test() {}
};
int main()
{ 
   Test *t;
}
复制代码

The above program works fine. There is no object being constructed, the program just creates a pointer of type “Test *”, so nothing is destructed. What about the below program?

复制代码
#include <iostream>
using namespace std;
 
class Test
{
private:
   ~Test() {}
};
int main()
{ 
   Test *t = new Test;
}
复制代码

The above program also works fine. When something is created using dynamic memory allocation, it is programmer’s responsibility to delete it. So compiler doesn’t bother.

The below program fails in compilation. When we call delete, desturctor is called.

复制代码
#include <iostream>
using namespace std;
 
class Test
{
private:
   ~Test() {}
};
int main()
{ 
   Test *t = new Test;
   delete t;
}
复制代码

We noticed in the above programs, when a class has private destructur, only dynamic objects of that class can be created. Following is a way to create classes with private destructors and have a function as friend of the class. The function can only delete the objects.

复制代码
#include <iostream>
 
// A class with private destuctor
class Test
{
private:
    ~Test() {}
friend void destructTest(Test* );
};
 
// Only this function can destruct objects of Test
void destructTest(Test* ptr)
{
    delete ptr;
}
 
int main()
{
    // create an object
    Test *ptr = new Test;
 
    // destruct the object
    destructTest (ptr);
 
    return 0;
}
复制代码

What is the use of private destructor?
Whenever we want to control destruction of objects of a class, we make the destructor private. For dynamically created objects, it may happen that you pass a pointer to the object to a function and the function deletes the object. If the object is referred after the function call, the reference will become dangling. See this for more details.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值