简体   繁体   English

如何在C ++中新建和初始化结构?

[英]How can I new and initialize a struct in C++?

In C, we actually do 在C中,我们实际上做了

struct node *p = (node*)malloc(sizeof(node));   // casting is not necessary
p->a = 0;      // first  element
p->b = NULL;   // second element

to dynamically allocate spaces in the memory, but how can I do this in C++ way? 动态分配内存中的空间,但是我该怎么用C ++的方式呢?

Is the line below a correct guess? 下面的线是正确的猜测吗?

node *p = new node {0, NULL};

Yes, you are correct. 是的,你是对的。

Assuming node is an aggregate, your C++ version is right (modulo NULL rather than nullptr ). 假设node是一个聚合,则您的C ++版本是正确的 (模NULL而不是nullptr )。

That being said, if these initial values are "defaults", you would conventionally write a default constructor to initialise those members for you automatically: 话虽如此,如果这些初始值是“默认值”,则通常会编写一个默认构造函数来自动为您初始化这些成员:

struct node
{
    int a;
    node* b;

    node() : a(0), b(nullptr) {}
};

Then you'd just write: 然后,您只需编写:

node* p = new node;

Or, better: 或更好:

auto p = std::make_unique<node>();

Or, better yet: 或者,更好的是:

node n;

Default-construction has some consequences though. 默认构造会带来一些后果。 You may not want any constructors. 您可能不需要任何构造函数。

In C++ you would avoid a naked new and either create a shared/unique pointer with std::make_shared / std::make_unique in C++11/14 or encapsulate the allocation in a handle-class following the RAII idiom. 在C ++中,您应该避免使用裸机,并在C ++ 11/14中使用std :: make_shared / std :: make_unique创建共享/唯一指针,或者按照RAII习惯用语将分配封装在句柄类中。

To give an example of how that would work: 举例说明如何工作:

class Foo {
    const int i;
    public:
    int j;
    Foo(int i) : i{i}, j{0} {}//constructor
    void foo() {std::cout << i << "\n";}
};

int main() {
    unique_ptr<Foo> fp = make_unique<Foo>(5);
    fp->foo();
    return 0;
}

In case the constructor looks a bit confusing to you, a short explanation: The colon after the constructors signature starts the initialization declaration. 如果构造函数看起来有些令人困惑,请简要说明一下:构造函数签名后的冒号开始初始化声明。 In this section you have to initialize const-values, but you can initialize all values there. 在本节中,您必须初始化const值,但是您可以在那里初始化所有值。 Thus constructors, which take arguments often look like this: 因此,带有参数的构造函数通常如下所示:

Foo(ArgType1 arg1, ArgType2 arg2,...,ArgTypeN argN) : 
   member1(arg1), member2(arg2), ... , memberN(argN) {//empty body}

Be sure to pay attention to the rule of three/five , when writing constructors. 编写构造函数时,请务必注意“三/五规则

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

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