如何定义指向 const 对象的可变指针?
我有一个类,其中包含一个指向类外部常量 VARIANT 值的指针,但有时我想更改此指针以引用类本身的 VARIANT 成员对象。
此类的大多数实例都是 const,因此我必须将指针声明为可变的。
在 Visual C++ 中,这段代码似乎做了我想要的事情:
VARIANT mutable const* m_value;
但是,由于可变是指针的属性而不是指针对象的属性,我认为这是正确的语法:
VARIANT const * mutable m_value;
类似于定义常量指针的方式(以及不是指向 const 对象的指针)。但 Visual C++ 不接受此变体。
警告 C4518:“可变”:存储类或类型说明符此处意外;忽略
Visual C++ 是对的,还是我遗漏了什么?另一个更符合标准的编译器的行为是否会有所不同?
I have a class that contains a pointer to a constant VARIANT value outside the class, but sometimes I want to change this pointer to refer to a VARIANT member object of the class itself.
Most instances of this class will be const, so I have to declare the pointer as mutable.
In Visual C++ this code seems to do what I want:
VARIANT mutable const* m_value;
However, since mutable is meant to be a property of the pointer and not the pointee, I would think this to be the correct syntax:
VARIANT const * mutable m_value;
Similar to how you define a constant pointer (and not a pointer to a const object). Visual C++ does not accept this variant though.
warning C4518: 'mutable ' : storage-class or type specifier(s) unexpected here; ignored
Is Visual C++ right, or am I missing something? Could another more standard-conformant compiler behave differently?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Comeau online 似乎同意 VC++ 在这里。
而且也是有道理的!类成员只能可变一次,并且不存在指向可变 const 对象的非常量指针。 “可变常量对象”没有意义。
您应该将
mutable
放在声明前面,因为它与static
位于同一区域:m_p3
不会使意义 - 您同时将成员声明为“always mutabel”和“always const”。Comeau online seems to agree with VC++ here.
And it also makes sense! A class member can only be mutable once and there is no such thing as a non-const pointer to a mutable const object. "Mutable const object" doesn't make sense.
You should put the
mutable
in front of your declaration, as it is in the same area as, for example,static
:m_p3
does not make sense - you declare the member as "always mutabel" and as "always const" at the same time.VC++是对的。在这种情况下,
mutable
是一个存储类说明符,如static
、extern
和register
。就像无法编译一样,说明符必须出现在声明的开头。
VC++ is right. In this case
mutable
is a storage-class-specifier, likestatic
,extern
andregister
. Just likewon't compile, as a specifier must appear at the beginning of a declaration.
请参阅如何定义指向 const 对象的可变指针?
See How do you define a mutable pointer to a const object?