1.第一种情况
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
using namespace std;
class Solution {
private:
~Solution() {
cout << "Destroy object" << endl;
}
public:
Solution() {
cout << "Create object" << endl;
}
friend void destruct(Solution*);
};
void destruct(Solution* s) {
delete s;
cout << "destroy over" << endl;
}
int main() {
Solution s; //(1)
Solution* s1 = new Solution; //(2)
destruct(s1);
return 0;
}
编译的结果: (1)构建对象出错, (2)正常原因: 构建一个私有的构造函数,the compiler would generate a compiler error for non-dynamically allocated objects because compiler need to remove them from stack segment once they are not in use.
2.第二种情况
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using namespace std;
class Solution {
private:
void *operator new(size_t);
public:
Solution() {
cout << "Create object" << endl;
}
~Solution() {
cout << "Destroy object" << endl;
}
};
int main() {
Solution s; //(1)
Solution* s1 = new Solution; //(2)
return 0;
}
编译的结果: (1)构建对象正常, (2)出错原因: 重载了new, 并私有化
近期评论