Reputation: 864
I'm trying to extract a const pointer to part way through an array. I found it works fine when using a vector, but won't compile (VS 2008) when using a valarray. Can somebody explain what the problem is?
struct vector_test
{
std::vector<int> v;
const int *pointy(const int i) const
{
return &(v[i]); // Ok
}
};
struct valarray_test
{
std::valarray<int> v;
const int *pointy(const int i) const
{
return &(v[i]); // error C2102: '&' requires l-value
}
};
Upvotes: 4
Views: 2551
Reputation: 62975
std::valarray<T>::operator [](std::size_t)
returns a T&
, which will work fine.
std::valarray<T>::operator [](std::size_t) const
returns a T
, which will be an rvalue and consequently cannot have its address taken.
Because valarray_test::pointy
is itself const
, valarray_test::v
is treated as const
and consequently the const
overload of operator[]
is called. Either make valarray_test::v
mutable
or make valarray_test::pointy
non-const
.
Upvotes: 13