普通new和placement new的重载

对于自定义对象,我们可以重载普通new操作符,这时候使用new Test()时就会调用到我们重载的普通new操作符。

示例程序:

 1 #include <iostream>
 2 #include <cstdlib>
 3 
 4 using namespace std;
 5 
 6 class Test
 7 {
 8 public:
 9     Test()
10     {
11         cout << "Test()" << endl;
12     }
13     
14     void* operator new(unsigned int size)
15     {
16         void* ret = malloc(sizeof(int) * size);
17         
18         cout << "normal new" << endl;
19         
20         return ret;
21     }
22     
23 
24 };
25 
26 
27 int main()
28 {    
29     Test* t = new Test();
30     
31     Test t2;
32 
33     
34     return 0;
35 }

执行结果如下:

调用placement new,程序如下:

 1 #include <iostream>
 2 #include <cstdlib>
 3 
 4 using namespace std;
 5 
 6 class Test
 7 {
 8 public:
 9     Test()
10     {
11         cout << "Test()" << endl;
12     }
13     
14     void* operator new(unsigned int size)
15     {
16         void* ret = malloc(sizeof(int) * size);
17         
18         cout << "normal new" << endl;
19         
20         return ret;
21     }
22     
23 
24 };
25 
26 
27 int main()
28 {    
29     Test* t = new Test();
30     
31     Test* t1 = new((void*)t)Test();
32     
33     Test t2;
34 
35     
36     return 0;
37 }

编译结果如下:

提示我们没有对应的函数,也就是placement new没有重载。

更改程序:

 1 #include <iostream>
 2 #include <cstdlib>
 3 
 4 using namespace std;
 5 
 6 class Test
 7 {
 8 public:
 9     Test()
10     {
11         cout << "Test()" << endl;
12     }
13     
14     void* operator new(unsigned int size)
15     {
16         void* ret = malloc(sizeof(int) * size);
17         
18         cout << "normal new" << endl;
19         
20         return ret;
21     }
22     
23     void* operator new(unsigned int size, void* loc)
24     {
25         cout << "placement new" << endl;
26         return loc;
27     }
28 
29 };
30 
31 
32 int main()
33 {    
34     Test* t = new Test();
35     
36     Test* t1 = new((void*)t)Test();
37     
38     Test t2;
39 
40     
41     return 0;
42 }

结果如下:

 再次给出一个测试程序:

 1 #include <iostream>
 2 #include <cstdlib>
 3 
 4 using namespace std;
 5 
 6 class Test
 7 {
 8 public:
 9     Test()
10     {
11         cout << "Test()" << endl;
12     }
13     
14     void* operator new(unsigned int size)
15     {
16         void* ret = malloc(sizeof(int) * size);
17         
18         cout << "normal new" << endl;
19         
20         return ret;
21     }
22     
23     void* operator new(unsigned int size, void* loc)
24     {
25         cout << "placement new" << endl;
26         return loc;
27     }
28 
29 };
30 
31 
32 int main()
33 {    
34     Test* t = new Test();
35     
36     Test* t1 = new((void*)t)Test();
37     
38     Test t2;
39 
40     Test* t3 = new((void*)&t2)Test();
41     
42     int a = 3;
43     
44     int* p = new((void*)&a)int(10);
45     
46     cout << "a = " << a << endl;
47     
48     return 0;
49 }

运行结果如下:

可以看到普通内置类型可以直接使用placement new。

原文地址:https://www.cnblogs.com/wanmeishenghuo/p/9651363.html