如何定义指向 const 对象的可变指针?

发布于 2024-09-30 10:31:30 字数 480 浏览 6 评论 0原文

我有一个类,其中包含一个指向类外部常量 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

骄兵必败 2024-10-07 10:31:30

Comeau online 似乎同意 VC++ 在这里。

而且也是有道理的!类成员只能可变一次,并且不存在指向可变 const 对象的非常量指针。 “可变常量对象”没有意义。

您应该将 mutable 放在声明前面,因为它与 static 位于同一区域:

class A {
  static  int const* m_p1; // static modifiable pointer to a const object;
  mutable int const* m_p2; // mutable pointer to a const object
  ...
  mutable int *const m_p3; // DOES NOT MAKE sense

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:

class A {
  static  int const* m_p1; // static modifiable pointer to a const object;
  mutable int const* m_p2; // mutable pointer to a const object
  ...
  mutable int *const m_p3; // DOES NOT MAKE sense

m_p3 does not make sense - you declare the member as "always mutabel" and as "always const" at the same time.

无畏 2024-10-07 10:31:30

VC++是对的。在这种情况下,mutable 是一个存储类说明符,如staticexternregister。就像

int const* static foo;

无法编译一样,说明符必须出现在声明的开头。

VC++ is right. In this case mutable is a storage-class-specifier, like static, extern and register. Just like

int const* static foo;

won't compile, as a specifier must appear at the beginning of a declaration.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文