2

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_; 
}

However gcc gives the following warning when compiling.

warning: type qualifiers ignored on function return type

Why is this warning provided by gcc? What does it mean? If this is not the right syntax for what I want, what is?

Matthew Hoggan
  • 7,402
  • 16
  • 75
  • 140

3 Answers3

2

The warning you get is because the final const is overlooked. Take it off and you're set.

You don't need to return a const pointer to const data, just a pointer to const data (which is const Type*). Just as it doesn't make sense to return a const int, it doesn't make sense to return a T* const, because as soon as the value is assigned to a new variable, that const is discarded.

zneak
  • 134,922
  • 42
  • 253
  • 328
1

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.

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.

Jesse Good
  • 50,901
  • 14
  • 124
  • 166
0

First const is right, the second const does not make any sense. Just look at this example:

const int foo();
int a = foo();

The fact if foo returns const int or just int does not change anything in this case. Same for Type *.

Slava
  • 43,454
  • 1
  • 47
  • 90