C++成员变量的new操作不应该放在构造函数中

C++成员变量的new操作不应该放在构造函数中:

理由如下:

https://blog.csdn.net/lmb1612977696/article/details/77850378#:~:text=C++%E7%B1%BB%E4%B8%AD%E7%9A%84

构造函数中尽量不要有new的操作,new的操作可以定义一个Init()来单独处理,代码如下:

 1 class Test{
 2 public:
 3     Test(){
 4         a_ = NULL;
 5         b_ = NULL;
 6         c_ = NULL;
 7     }
 8     void Init(){
 9         a_ = new A;
10         b_ = new B;
11         c_ = new C;
12     }
13     ~Test(){
14         delete a_;
15         delete b_;
16         delete c_;
17     }
18 private:
19     A* a_;
20     B* b_;
21     C* c_;
22 };

 

posted @ 2024-09-04 10:26  量子与太极  阅读(7)  评论(0编辑  收藏  举报