bandaoyu 2021-09-25 10:39 采纳率: 55.6%
浏览 10

C++11的allocator::construct如何构造多参数对象?

allocator::construct的用法,在构造和函数只有一个参数时,我们很容易知道它的用法是这样:

//#include "CAnimal.h"
#include <memory>
#include <iostream>
 
using namespace std;
 
class Animal
{
public:
#if 0        //即使为0,没有默认构造也是可以,
    Animal() : num(0)
    {
        cout << "Animal constructor default" << endl;
    }
#endif
    Animal(int _num) : num(_num)
    {
        cout << "Animal constructor param" << endl;
    }
 
    ~Animal()
    {
        cout << "Animal destructor" << endl;
    }
 
    void show()
    {
        cout << this->num << endl;
    }
 
private:
    int num;
};
 
/*
    由于allocator将内存空间的分配和对象的构建分离
    故使用allocator分为以下几步:
    1.allocator与类绑定,因为allocator是一个泛型类
    2.allocate()申请指定大小空间
    3.construct()构建对象,其参数为可变参数,所以可以选择匹配的构造函数
    4.使用,与其它指针使用无异
    5.destroy()析构对象,此时空间还是可以使用
    6.deallocate()回收空间
*/
 
int main()
{
    allocator<Animal> alloc;        //1.
    Animal *a = alloc.allocate(5);    //2.
 
    //3.
    /*void construct(U* p, Args&&... args);
   在p指向的位置构建对象U,此时该函数不分配空间,pointer p是allocate分配后的起始地址
   constructor将其参数转发给相应的构造函数构造U类型的对象,相当于 ::new ((void*) p) 
   U(forward<Args> (args)...);
   */
    alloc.construct(a, 1);
    alloc.construct(a + 1);
    alloc.construct(a + 2, 3);
    alloc.construct(a + 3);
    alloc.construct(a + 4, 5);
 
    //4.
    a->show();
    (a + 1)->show();
    (a + 2)->show();
    (a + 3)->show();
    (a + 4)->show();
 
    //5.
    for (int i = 0; i < 5; i++)
    {
        alloc.destroy(a + i);
    }
    //对象销毁之后还可以继续构建,因为构建和内存的分配是分离的
    //6.
    alloc.deallocate(a, 5);
 
    cin.get();
    return 0;
}

但是当我将上面的构造函数变成2个参数时:

 
……  
  Animal(int _num,int _weight) : num(_num),weight(_weight)
    {
        cout << "Animal constructor param" << endl;
    }
 
……
 
    void show()
    {
        cout <<“num:”<< this->num << endl;
        cout << "weight:" << this->weight<< endl;
    }
 
private:
    int num;
    int weight;
};

我想这样使用:

alloc.construct(a , 3,600);

alloc.construct(a + 1, 5,300);

……

会报错

 

我这样用才可以:

alloc.construct(a , Animal(3,600));

alloc.construct(a + 1,Animal( 5,300));

……

请问必须这样用吗?不能alloc.construct(a + 1, 5,300); 这样直接列参数使用?

  • 写回答

1条回答 默认 最新

  • CSDN-Ada助手 CSDN-AI 官方账号 2022-09-07 17:38
    关注
    不知道你这个问题是否已经解决, 如果还没有解决的话:

    如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 以帮助更多的人 ^-^
    评论

    报告相同问题?

    问题事件

    • 创建了问题 9月25日

    悬赏问题

    • ¥15 我现在有一些关于提升机故障的专有文本数据,量也不多,我在label studio上进行了关系和实体的标注,完成了知识图谱的构造,那么我使用生成式模型的话,我能做哪些工作来写我的论文?
    • ¥15 电脑连不上无线网络如下诊断反馈应该如何操作
    • ¥15 telegram api 使用forward_messages方法转发消息时,目标群组里面会出现此消息来源,如何隐藏?
    • ¥15 在ubuntu中无法连接到远程服务器传输文件
    • ¥15 关于#tensorflow#的问题:有没有什么方法可以让机器自己学会像素风格的图片
    • ¥15 Oracle触发器字段变化时插入指定值
    • ¥15 docker无法进入容器内部
    • ¥15 qt https 依赖openssl 静态库
    • ¥15 python flask 报错
    • ¥15 改个密码引发的项目启动问题