贵阳网站托管,网站优化排名网站,做网站的后台开发需要会些什么,沈阳快速排名优化前置知识#xff1a;
new的类对象需要手动delete。且使用堆空间。且只能用指针接收。
直接创建的类对象创建在栈中#xff08;或说堆栈#xff09;。不需要手动delete#xff0c;随着生存周期的结束#xff08;如所在的函数return了#xff09;而释放#xff0c;和堆栈…前置知识
new的类对象需要手动delete。且使用堆空间。且只能用指针接收。
直接创建的类对象创建在栈中或说堆栈。不需要手动delete随着生存周期的结束如所在的函数return了而释放和堆栈空间一起释放了。 为什么要私有构造函数
把析构函数定义为私有的就阻止了用户在类域外对析构函数的使用。这表现在如下两个方面 1. 禁止用户对此类型的变量进行定义即禁止在栈内存空间内创建此类型的对象。要创建对象只能用 new 在堆上进行。 2. 禁止用户在程序中使用 delete 删除此类型对象。对象的删除只能在类内实现也就是说只有类的实现者才有可能实现对对象的 delete用户不能随便删除对象。如果用户想删除对象的话只能按照类的实现者提供的方法进行。 可见这样做之后大大限制了用户对此类的使用。一般来说不要这样做通常这样做是用来达到特殊的目的比如在 singleton单例模式 的实现上。
私有构造函数私有析构函数的几个例子 注意这里getInstance的实现不能保证单例。
例1
#include iostreamusing 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 iostreamusing 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 iostreamusing 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 iostreamusing 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 iostreamusing 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出来的所以需要手动deletereturn 0;
}
正常输出 construct A xigou A 参考链接
https://blog.csdn.net/koudaidai/article/details/7546661