我在指向结构的类上有一个unique_ptr成员。

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

我不明白如何获取该结构的内存并设置unique_ptr。

在我的构造函数中,我有:
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
}

我究竟做错了什么?

最佳答案

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

}

...或者如果您想稍后转让所有权(您也可以在构造函数中执行此操作,但不能清楚地传达您要执行的操作)
_character_state.reset( new StateStruct() );

...或出于完整性考虑,如果您喜欢键入内容,可以为变量分配一个新的unique_ptr
_character_state = std::unique_ptr<someObject>(new someObject());

09-06 22:30