【C++学习】对私有构造析构函数的思考:new一个类对象vs直接创建类对象

前置知识:

new的类对象需要手动delete。且使用堆空间。且只能用指针接收。

直接创建的类对象创建在栈中(或说堆栈)。不需要手动delete,随着生存周期的结束(如所在的函数return了)而释放,和堆栈空间一起释放了。

为什么要私有构造函数?

把析构函数定义为私有的,就阻止了用户在类域外对析构函数的使用。这表现在如下两个方面:   
    
  1.   禁止用户对此类型的变量进行定义,即禁止在栈内存空间内创建此类型的对象。要创建对象,只能用   new   在堆上进行。   
    
  2.   禁止用户在程序中使用   delete   删除此类型对象。对象的删除只能在类内实现,也就是说只有类的实现者才有可能实现对对象的   delete,用户不能随便删除对象。如果用户想删除对象的话,只能按照类的实现者提供的方法进行。   
    
  可见,这样做之后大大限制了用户对此类的使用。一般来说不要这样做;通常这样做是用来达到特殊的目的,比如在   singleton(单例模式)   的实现上。

私有构造函数,私有析构函数的几个例子:

 注意这里getInstance的实现不能保证单例。

例1

#include <iostream>

using namespace std;
class A {
   public:
    static A* getInstance() { return new A; }
    void Distroy() { delete this; }

   private:
    A() { cout << "construct A" << endl; }
    ~A() { cout << "xigou A" << endl; }
};
int main() {
    A* a_ptr = new A;
    return 0;
}

报错:

error: calling a private constructor of class 'A'

例2

#include <iostream>

using namespace std;
class A {
   public:
    static A* getInstance() { return new A; }
    void Distroy() { delete this; }

   private:
    A() { cout << "construct A" << endl; }
    ~A() { cout << "xigou A" << endl; }
};
int main() {
    A a;
    return 0;
}

报错

error: calling a private constructor of class 'A'

error: variable of type 'A' has private destructor

例3

#include <iostream>

using namespace std;
class A {
   public:
    static A* getInstance() { return new A; }
    void Distroy() { delete this; }

   public:
    A() { cout << "construct A" << endl; }

   private:
    ~A() { cout << "xigou A" << endl; }
};
int main() {
    A a;
    return 0;
}

报错:

error: variable of type 'A' has private destructor

 记住析构函数不能重载,所以没法既定义public的也定义private的。

例4

#include <iostream>

using namespace std;
class A {
   public:
    static A* getInstance() { return new A; }
    void Distroy() { delete this; }

   public:
    A() { cout << "construct A" << endl; }

   private:
    ~A() { cout << "xigou A" << endl; }
};
int main() {
    A* a_ptr = new A;
    return 0;
}

正常输出:

construct A

例5:

#include <iostream>

using namespace std;
class A {
   public:
    static A* getInstance() { return new A; }
    void Distroy() { delete this; }

   private:
    A() { cout << "construct A" << endl; }
    ~A() { cout << "xigou A" << endl; }
};
int main() {
    A* a_ptr = A::getInstance();
    a_ptr->Distroy();//这句没有也可以正常编译,因为对象是new出来的,所以需要手动delete!
    return 0;
}

正常输出:

construct A

xigou A

参考链接:

https://blog.csdn.net/koudaidai/article/details/7546661

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值