C ++在类变量中分配矢量大小,而无需默认初始化 [英] C++ Allocate Vector Size in class variable without default initialization

查看:123
本文介绍了C ++在类变量中分配矢量大小,而无需默认初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我有一个类(HostObject),其中包含一个复杂类向量(object1).如下面描述的伪代码

So I have a class (HostObject) that has a vector of complex classes (object1) inside it. Such as the pseudocode depicted below

#DEFINE ARRAY_SIZE 10
class HostObject {
    //other member variables
    vector<Object1> vec(ARRAY_SIZE);

    //default constructor
    HostObject(){
        //leave vector default constructed
    }

    //my custom constructor
    HostObject(double parmeter1, double parameter2, doubleparameter3) {

        //some code doing some calculations 

        for (int i = 0; i <ARRAY_SIZE; i++){

            vec.push_back(Object1( double p1, int p2, double p3, intp4));

        }
    }
}

我知道在创建HostObject的任何时间编写此代码的方式,将使用默认构造的Object1s初始化矢量.我的代码需要一个向量,所以我希望编译器知道向量的大小,以便它可以适当地分配向量所需的内存.我知道如果我想要更动态的分配,可以使用储备金.

I know the way this code is written any time HostObject is created the vector will be initialized with default constructed Object1s. My code requires a vector so I would like the compiler to know what the size of the vector is so it can appropriately allocate the memory needed for my vector. I know I could use reserve if I wanted a more dynamic allocation.

我想我的问题是: 他们在定义矢量时是否需要为矢量保留空间的方式,而无需默认初始化对象或使用reserve函数?

I guess my question is: Is their a way to reserve space for a vector when defining it that does not require default initialization of the objects in it or use of the reserve function?

我的目标是分配内存空间,因此当我构造HostObject类型的对象数组时,将为get分配正确的内存量.是否会根据默认构造函数的结果确定对象的内存大小?

My goal is to have the memory space allocated so when I construct an array of objects of HostObject type the get allocated the correct amount of memory. Does the memory size of an object get determined based on the result of the default constructor?

推荐答案

std::vector没有用于保留容量的构造函数.保留容量的唯一方法是使用reserve成员函数.

There is no constructor for std::vector for for reserving capacity. The only way you can reserve capacity is to use reserve member function.

#DEFINE ARRAY_SIZE 10
class HostObject {
    //other member variables
    vector<Object1> vec;

    //default constructor
    HostObject(){
        vec.reserve(ARRAY_SIZE);
    }

    //my custom constructor
    HostObject(double parmeter1, double parameter2, doubleparameter3) {
        vec.reserve(ARRAY_SIZE);
        //some code doing some calculations 

        for (int i = 0; i <ARRAY_SIZE; i++){

            vec.push_back(Object1( double p1, int p2, double p3, intp4));

        }
    }
}

了解有关std::vector

这篇关于C ++在类变量中分配矢量大小,而无需默认初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆