Kevin Dong
Kevin Dong

Reputation: 5369

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

In C, we actually do

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?

Is the line below a correct guess?

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

Upvotes: 6

Views: 14366

Answers (2)

midor
midor

Reputation: 5557

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.

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. 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.

Upvotes: 1

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385385

Yes, you are correct.

Assuming node is an aggregate, your C++ version is right (modulo NULL rather than 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.

Upvotes: 9

Related Questions