Const and non-const in stl containers

The STL vector template defines elements of access to elements of both const and non-const variants, for example:

reference operator[](size_type __n) 
    {return *(this->_M_impl._M_start + __n);}
const_reference operator[](size_type __n) const 
    {return *(this->_M_impl._M_start + __n);}

When does the compiler decide to use one version on top of another? The vector itself is not defined as const, and elements are not stored in it. Therefore, two functions are specified:

A f(int i) const
    { return myVector[i]; }
A f(int i)
    { return myVector[i]; }

My understanding is that the first will call the const version of the [] operator and return const A. The second will call the non-constant version and return the non-constant A?

For me, the first version of f () seems to be “correct” for writing, since the function does not change anything, but the caller may be surprised that it returns constant A. Of course, if I wanted to return const A, I need to define f () as:

const A f(int i) const    //Note the extra const at the start
    { return myVector[i]; }

To say, no matter who writes to the caller, to expect the const to return.

, ? const, boost:: ptr_vector, std::vector? ? ? ?

+5
4

. -, cv- cv-qualifiers , this. ++, this, :

reference operator[](this_type this, size_type n);
const_reference operator[](const this_type this, size_type n);

, , on, const, . , . , const_reference , const, reference , const. const_reference , .

const_reference const reference, ; reference - , . const_reference, , .

+7

const - , *this const-.

struct A {
  void f(int i) const;
  void f(int i);
};

void g(const A& x, A& y) {
  x.f(); // calls const version
  y.f(); // calls non-const version
}

STL , . const.

+1

:

A f(int i) const
    { return myVector[i]; }

non-const A. , , [] ( ), A. "" , " . , :

struct B {
  const A& f(int i) const;
  A& f(int i);

private:
  vector<A> myVector;
};

f(), const B:

const B b;
const A& a = b.f();

a .

+1

Returning a constant value is virtually pointless - it is completely legal to build a new value from the lvalue constant, so the first form is valid. Think about it - if you want to copy something, it doesn't matter if you can write somewhere.

If you returned the link, the compiler will not allow you to return A & in the const version.

0
source

All Articles