When writing:
std::vector<double> vec{1.0,2.0};
std::span<const double> s(vec);
s[0]=1.0;
I get a compiler error, as expected:
Cannot assign to return value because function 'operator[]' returns a const value
However, when I go and see the return type of std::span::operator[]
, I only see a reference
return, not a const reference
return, while I was expecting a decltype(auto)
for the return type.
Why do I not get an error that the operator with const reference
is not implemented? How does the compiler figure out the correct answer?
When writing:
std::vector<double> vec{1.0,2.0};
std::span<const double> s(vec);
s[0]=1.0;
I get a compiler error, as expected:
Cannot assign to return value because function 'operator[]' returns a const value
However, when I go and see the return type of std::span::operator[]
, I only see a reference
return, not a const reference
return, while I was expecting a decltype(auto)
for the return type.
Why do I not get an error that the operator with const reference
is not implemented? How does the compiler figure out the correct answer?
1 Answer
Reset to default 6If the type of T
is const double
, then the return of T&
is const double&
.
The qualifiers, like const
or volatile
are part of the type that is held by the span, and are transitive to the returned reference of the operator[]
.