0

Probably it's cause i didn't sleep all the night...but can someone explain me why the first operator[] (the const one) generates a warning in MSVC 2010 saying that i'm returning the address of a temorary variable, and the second operator[] (the non-const one) produces a compiler error stating: 'return' : cannot convert from 'std::_Vb_reference<_Alloc>' to 'bool &' ?!?!?

Thanks a lot to everyone will waste time on my question.

    class ReqAtts
    {
    public:
        const bool& operator[](size_t ii) const
        {
            return _atts[ii];
        }

        bool& operator[](size_t ii)
        {
            return _atts[ii];
        }

    private:
        std::vector<bool> _atts;

    };
Guido Ranzuglia
  • 371
  • 2
  • 13
  • One thing that I noticed immediately is that in the second function your parameter is "att" but you're indexing "ii" into the array. – Hawkmooon Jun 30 '15 at 05:27
  • 4
    `std::vector` is actually treated as a special case in C++. [This answer](http://stackoverflow.com/a/17794965) should help explain why. – huu Jun 30 '15 at 05:28
  • thanks a lot to huu for the useful link :) – Guido Ranzuglia Jun 30 '15 at 05:33

2 Answers2

1

std::vector<bool> is space efficient in most implementations (g++, MSVC): every item may be stored as a single bit, not as bool. You can read more here: en.cppreference.com

You have 2 options:

  1. Use std::vector<unsigned char> (or other integer type) instead of std::vector<bool>.
  2. Use std::vector<bool>::reference as return type for operator[] as follows:

    class ReqAtts
    {
    public:
        std::vector<bool>::const_reference operator[](size_t ii) const
        {
            return _atts[ii];
        }
    
        std::vector<bool>::reference operator[](size_t ii)
        {
            return _atts[ii];
        }
    
    private:
        std::vector<bool> _atts;
    
    };
    
  • considering that the _atts vector is static (must have always the same dimension...nine, it's quite small) the best option is to use a good old c array. Anyway, your solutions are good as well :) Thanks a lot! – Guido Ranzuglia Jun 30 '15 at 06:17
-1

Change Parameter att to ii , it will work

class ReqAtts
    {
    public:
        const bool& operator[](size_t ii) const
        {
            return _atts[ii];
        }

        bool& operator[](size_t ii)
        {
            return _atts[ii];
        }

    private:
        std::vector<bool> _atts;

    };
mystic_coder
  • 462
  • 2
  • 10