c++ const 成员函数,返回一个 const 指针.但是返回的指针是什么类型的 const?

2022-01-23 00:00:00 constants c++

如果有人问过这个问题,我深表歉意,但是如何在 C++ 中创建一个返回以下场景中的指针的成员函数:1.返回的指针是常量,但是里面的垃圾是可以修改的.2.里面的垃圾是常量,但是返回的指针可以修改.3. 垃圾和指针都不能修改.

I apologize if this has been asked, but how do I create a member function in c++ that returns a pointer in the following scenerios: 1. The returned pointer is constant, but the junk inside can be modified. 2. The junk inside is constant but the returned pointer can be modified. 3. Neither the junk, nor the pointer can be modified.

是这样吗:

  1. int *const func() const
  2. const int* func() const
  3. const int * const func() const

我读过的所有教程都没有涵盖这种区别.

All of the tutorials I've read don't cover this distinction.

旁注:如果我的方法被声明为 const ,那么教程会说我不会修改参数.但是在参数是指针的情况下,这对我来说还不够清楚.我的参数是否需要像:

Side note: If my method is declared const then the tutorials say that I'm stating that I won't modify the parameters.. But this is not clear enough for me in the case when a parameter is a pointer. Do my parameters need to be like:

一个.void func(const int* const x) const;
湾.void func(const int* x) const;
C.void func(const int* const x) const;

推荐答案

我不知道你读了什么书,但是如果你标记一个方法 const 意味着 this 将是类型const MyClass* 而不是 MyClass*,这反过来意味着您不能更改未声明为 mutable 的非静态数据成员,也不能在 this 上调用任何非 const 方法.

I don't know what book you have read, but if you mark a method const it means that this will be of type const MyClass* instead of MyClass*, which in its turn means that you cannot change nonstatic data members that are not declared mutable, nor can you call any non-const methods on this.

现在是返回值.

1 .int * const func () const

函数是常量,返回的指针是常量,但垃圾内部"可以修改.但是,我认为返回 const 指针没有意义,因为最终的函数调用将是一个右值,并且非类类型的右值不能是 const,这意味着 const 将无论如何都会被忽略

The function is constant, and the returned pointer is constant but the 'junk inside' can be modified. However, I see no point in returning a const pointer because the ultimate function call will be an rvalue, and rvalues of non-class type cannot be const, meaning that const will be ignored anyway

2 .const int* func () const

这是一个有用的东西.里面的垃圾"不能修改

This is a useful thing. The "junk inside" cannot be modified

3 .const int * const func() const

由于1中的原因,语义上与2几乎相同.

semantically almost the same as 2, due to reasons in 1.

HTH

相关文章