似乎无法将unique_ptr赋值给结构体
Cannot seem to assign a unique_ptr to a struct
在类上有一个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
相关文章:
- 为"adjacent"变量赋值时出现问题
- C++中的赋值发生,尽管右侧出现异常
- 用C++中的sscanf赋值
- 为std::string的某个索引赋值
- 重载Singly Linked List中的赋值运算符
- 为什么我必须在C++中添加一个赋值符号来声明一个数组
- gtest_使用setargpointee在函数中赋值
- 非常量变量只读位置的赋值
- 使用赋值运算符重载从类中返回jobject
- C++数据文件、数组和计算赋值
- 为什么在使用转换构造函数赋值后调用C++类的析构函数?
- 全局作用域中函数指针的赋值
- 在以唯一ptr为值的C++映射中,动态内存何时会被销毁
- 错误:在为指针赋值时,void值没有被忽略
- 标准库类型的赋值运算符的引用限定符
- 关于 c++ 函数中指针赋值的简单问题
- 复制构造函数、赋值运算符C++
- 标准::变体的赋值运算符
- cin >> int 给定一个字符串将 int 赋值为 0
- 在C++中为空 ptr 到 ptr 赋值