简体   繁体   English

C ++构造函数初始化堆栈中的非基本成员变量

[英]C++ Constructor Initialize Non Primitive Member Variables In Stack

I've a basic question about C++ constructors. 我有一个关于C ++构造函数的基本问题。

Let's say that I have a class definition something like this: 假设我有一个类似这样的类定义:

class Project {
public:
    int time;
    std::vector<Task> tasks;

    Project();
};

I want to initialize this vector in my source file, however I'm not sure about the correct and efficient way to do this. 我想在源文件中初始化此向量,但是我不确定执行此操作的正确和有效方法。

Project::Project() {
    time = 0;
    tasks = std::vector<Task>();
}

Is this a correct way to initialize object in the stack? 这是初始化堆栈中对象的正确方法吗?

Vectors can use custom allocators, so you may be able to use a vector class specialized for a custom allocator (like this one ). 向量可以使用自定义分配器,因此您可以使用专门用于自定义分配器的向量类(例如this )。

However, you cannot use the stack of the constructor itself, as it becomes invalidated after the constructor finishes. 但是,您不能使用构造函数本身的堆栈,因为它在构造函数完成后会失效。 You either need to allocate the memory in the object itself (in the linked example, make the arena a member of the class) or receive it as a parameter to the constructor. 您要么需要在对象本身中分配内存(在链接的示例中,使arena成为类的成员),要么将其作为构造函数的参数接收。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM