返回指针到不可修改的成员数组C ++ gcc警告 [英] Return Pointer To Non-Modifiable Member Array C++ gcc warning
问题描述
我想返回一个指向类拥有的数组的指针.但是,我不想允许用户修改该数据或指针.根据我的理解,您需要使用以下语法返回指向常量数据的常量指针.
I would like to return a pointer to an array owned by a class. However, I do not want to allow users to modify that data or pointer. According to how I understand things you need return a constant pointer to constant data using the following syntax.
const Type *const Class::Method() {
return this->data_;
}
但是,gcc在编译时会发出以下警告.
However gcc gives the following warning when compiling.
警告:函数返回类型时忽略类型限定符
warning: type qualifiers ignored on function return type
为什么gcc会提供此警告?这是什么意思?如果这不是我想要的正确语法,那是什么?
Why is this warning provided by gcc? What does it mean? If this is not the right syntax for what I want, what is?
推荐答案
对于内置类型,顶级const
被忽略.因为在C ++ [3.14p4]中有一条规则:class and array prvalues can have cv-qualified types; other prvalues always have cv-unqualified types.
.对于您的情况const Type* const
,将使指针const
的顶级const
被忽略.
The top level const
is ignored for built-in types. As there is a rule in C++[3.14p4]: class and array prvalues can have cv-qualified types; other prvalues always have cv-unqualified types.
. In your case const Type* const
, the top level const
making the pointer const
is ignored.
您可以在末尾添加const
:const Type * Class::Method() const {...}
.这样可以防止在成员函数内部修改指针. 但是,由于成员函数返回的prvalue不可修改,因此不必这样做以防止在类外部修改指针成员(这也是该规则存在的原因在C ++中).当您要使用对Class
对象等的常量引用来调用该函数时,这可能会很有用,但是对于您正在执行的操作,这似乎没有必要.
You could add const
to the end: const Type * Class::Method() const {...}
. This would prevent the pointer from being modified inside the member function. However, since the member function returns prvalue which is non-modifiable, it is not necessary to do this to prevent modification of the pointer member outside of the class (and this is also the reason why this rule exists in C++). It may be useful when you want to call the function with a constant reference to a Class
object, etc., but for what you are doing, this doesn't seem necessary.
这篇关于返回指针到不可修改的成员数组C ++ gcc警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!