且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-04-25 04:50:35

我不知道你读了什么书,但是如果你标记一个方法 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