错误:分配数据成员 ‘RootBoxT::innerBox_’在只读结构中
我遇到了一个错误,如主题所示:在只读结构中分配数据成员 'RootBoxT
。我“可能”知道为什么会发生这种情况,但我需要更多地了解规则。
我将 RootBoxT
的所有实例都设置为 const
,并且 RootBoxT
类的成员变量 *innerBox_
也是 >const
类型。在类RootBoxT
的方法之一中,我需要更新*innerBox_
,因此我调用delete
来释放的内存innerBox_
并为其分配了另一个 const 指针。
我的问题是:
- 当我需要更新 const 指针的值时,我只需删除它并用另一个 const 指针分配它,这是正确的方法吗?
- 此错误是否是由于
RootBoxT
的实例是const
但其中一个方法更改了成员变量指向的位置而引起的?如果不是,为什么会发生这种情况?如果是这样,我应该将这些实例更改为非常量吗?
我真的搞砸了我当前项目的 const 关键字,因为我对 C++ 相当陌生。谢谢。
I encountered an error as the topic says: assignment of data-member ‘RootBoxT<CORE::DoubleWrapper>::innerBox_’ in read-only structure
. I "might" know why does this happen, but I need to learn more about the rules.
I made all instances for RootBoxT
as const
, and the member variable *innerBox_
of class RootBoxT
is also const
type. In one of the methods of class RootBoxT
, I need to update the *innerBox_
, so I called delete
to free the memory of innerBox_
and assigned it with another const pointer.
My questions is that:
- Is this the right method, that when I need to update the value of a const pointer, I just delete it and assign it with another const pointer?
- Is this error cause by the fact that the instance of
RootBoxT
isconst
but one of the methods changed the place that a member variable points to? If not, why does it happen? If so, should I just change these instances to non-const?
I really messed up with const
keyword for my current project, as I'm rather new to C++. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果你有这样的东西:
和一个
const S
对象 (s
),指针si
是const
但不是它指向的int
(*si
)。这意味着您可以写:但不能写:
因为这会修改指针值,而不是它指向的值。
If you have something like this:
and a
const S
object (s
), the pointers.i
isconst
but not theint
it points to (*s.i
). This means you can write:but not:
because that would modify the pointer value, not what it points to.