Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer into vector, but not into a valarray?

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
    }
};
like image 448
wxffles Avatar asked Nov 03 '25 16:11

wxffles


1 Answers

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.

like image 163
ildjarn Avatar answered Nov 05 '25 07:11

ildjarn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!