adelphospro
adelphospro

Reputation: 165

Cannot seem to assign a unique_ptr to a struct

I have a unique_ptr member on a class that points to a struct.

class ExampleClass {
    std::unique_ptr<StateStruct> _character_state;
}

I don't understand how to acquire the memory for the struct and set the unique_ptr.

In my constructor I have:

ExampleClass::ExampleClass {
    std::unique_ptr<StateStruct> _character_state(static_cast<StateStruct*>(malloc(sizeof(StateStruct))));
    _character_state->state_member_int_value = 4 // _character_state is empty
}

What am I doing wrong?

Upvotes: 2

Views: 6531

Answers (3)

Slava
Slava

Reputation: 44238

What am I doing wrong?

First of all your syntax is wrong, you are missing brackets. Second, inside your constructor you are creating local variable _character_state which would hide member variable and leave it uninitialized. So proper syntax is:

ExampleClass::ExampleClass() :
    _character_state( std::make_unique<StateStruct>() )
{
    _character_state->state_member_int_value = 4 // _character_state is empty
}

If you, for watever reason, have to create StateStruct with malloc(), you would need to supply custom deleter, that calls free().

If you do not really need malloc() you probably should initialize state_member_int_value inside StateStruct own constructor.

Upvotes: 0

learnvst
learnvst

Reputation: 16195

ExampleClass::ExampleClass() : _character_state( new StateStruct() ) {

}

... or if you want to transfer ownership at some point later (you could do this in the constructor also, but does not convey what you are trying to do as clearly)

_character_state.reset( new StateStruct() );

... or in the interests of completeness, you can assign a fresh unique_ptr to your variable if you enjoy typing

_character_state = std::unique_ptr<someObject>(new someObject());

Upvotes: 2

Loki Astari
Loki Astari

Reputation: 264331

Well don't use malloc.

std::unique_ptr<StateStruct> _character_state(static_cast<StateStruct*>(malloc(sizeof(StateStruct))));
                                                                        ^^^^^^

The unique_ptr release the memory with a call to delete (not free).

Also you are creating a local variable inside the constructor (not initializing the member variable). Prefer to initialize member variables inside the initializer list not in the body of the constructor.

ExampleClass::ExampleClass {
    _character_state(new StateStruct)
{
    // Should you not move this to the constructor
    // if StateStruct
    _character_state->state_member_int_value = 4
}

Upvotes: 1

Related Questions