• (转载)网易校园招聘c++题目如何让new操作符不分配内存,只调用构造函数


    (转载)http://blog.csdn.net/ctthunagchneg/article/details/8608142

    问题:c++中的new操作符 通常完成两个工作 分配内存及调用相应的构造出世核函数。
    请问:
    1)如何让new操作符不分配内存,只调用构造函数?
    2) 这样的用法有什么用?

    解答:(要求new显式调用构造函数,但不分配内存。)

    题目要求不能生成内存 还要调用构造函数 说明这个类里面没有对内部操作 但可以对外部操作 比如static的数

    摘录:如果我是用new分配对象的,可以显式调用析构函数吗?
    可能不行。除非你使用定位放置 new.

    #include <iostream>
    #include <string>
    #include <cstdio>
    
    using namespace std;
    
    class Fred
    {
    public:
        Fred() {cout << "fred" << endl;}
        ~Fred() {cout << "~fred" << endl;}
    };
    
    int main(int argc, char** argv)
    {
        Fred* f = new ((void*)10000)Fred();
        printf("%d\n", f);
    
        return 0;
    }

    2)
    定位放置new(placement new)有很多作用。最简单的用处就是将对象放置在内存中的特殊位置。这是依靠 new表达式部分的指针参数的位置来完成的:

     

    #include <new>        // 必须 #include 这个,才能使用 "placement new"
    #include "Fred.h"     // class Fred 的声明

    void someCode()
    {
       char memory[sizeof(Fred)];     // Line #1
       void* place = memory;          // Line #2

       Fred* f = new(place) Fred(); // Line #3 (详见以下的“危险”)
       // The pointers f and place will be equal

       // ...
    }
    Line #1 在内存中创建了一个sizeof(Fred)字节大小的数组,足够放下 Fred 对象。Line #2 创建了一个指向这块内存的首字节的place指针(有经验的 C 程序员会注意到这一步是多余的,这儿只是为了使代码更明显)。Line #3 本质上只是调用了构造函数 Fred::Fred()。Fred构造函数中的this指针将等于place。因此返回的 f 将等于place。  
    Line #3 本质上只是调用了构造函数 Fred::Fred()。

    *********************************************************

    placement new的作用就是:创建对象但是不分配内存,而是在已有的内存块上面创建对象。

    用于需要反复创建并删除的对象上,可以降低分配释放内存的性能消耗。

    #include <iostream>
    #include <new>
    using namespace std;
    
    const int chunk = 16;
    class Foo
    {
    public:
        int val( ) { return _val; }
        Foo( ) { _val = 0; }
    
    private:
        int _val;
    };
    
    //预分配内存,但没有Foo对象
    char*buf = new char[ sizeof(Foo) * chunk ];
    
    int main()
    {
        //在buf中创建一个Foo对象
        Foo*pb = new (buf) Foo;
    
        //检查一个对象是否被放在buf中
        if ( pb->val() == 0 )
        {
            cout <<"new expression worked!" <<endl;
        }
    
        //到这里不能再使用pb
        delete[] buf;
    
        return 0;
    }
  • 相关阅读:
    基于摸板匹配的目標跟蹤算法
    spoj 2713 Can you answer these queries IV
    zoj 3633 Alice's present
    hdu 3642 Get The Treasury
    poj 1195 Mobile phones
    poj 2760 End of Windless Days
    zoj 3540 Adding New Machine
    spoj 1716 Can you answer these queries III
    spoj 1043 Can you answer these queries I
    spoj 2916 Can you answer these queries V
  • 原文地址:https://www.cnblogs.com/Robotke1/p/3092732.html
Copyright © 2020-2023  润新知