似乎无法将unique_ptr赋值给结构体

Cannot seem to assign a unique_ptr to a struct

本文关键字:ptr 赋值 结构体 unique      更新时间:2023-10-16

在类上有一个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());

我们不要使用malloc。

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

unique_ptr通过调用delete(非free)释放内存。

您还在构造函数中创建了一个局部变量(而不是初始化成员变量)。首选在初始化列表中初始化成员变量,而不是在构造函数体中。

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

我做错了什么?

首先你的语法是错误的,你缺少括号。其次,在构造函数中创建局部变量_character_state,它将隐藏成员变量并使其未初始化。正确的语法是:

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

如果出于任何原因,必须用malloc()创建StateStruct,则需要提供自定义删除器,该删除器调用free()

如果你不需要malloc(),你可能应该在StateStruct自己的构造函数中初始化state_member_int_value