简体   繁体   中英

const vector reference overloading

For simplicity just pass part of the code.

class A {
public:
std::vector<int> & get(){ return myVector;}
const std::vector<int> & get() const {return myVector;}
private:
   std::vector<int> myVector;
}

My question is how to involve overloaded const get method. When I try to create const_iterator and debug code it involves non-const method. Want to understand how it works I use the following snippets

A myA;
myA.get().push_back(1);
for (const auto& v: myA.get()) { } // it involve not const get method

or

std::vector<int>::const_iterator cit = myA.get().begin()
//it involves not const method

or

 const std::vector< int > v = myA.get( );
 // involves non-const method

or even I create function:

int constVector( const std::vector< int > &constVector )
{
   return constVector[0];
}

int b = constVector( myA.get( ) ); // it involves non-const method

What is the purpose of overloaded const method if they are not involved.

And what i doing wrong and how i can involve the const method.

Since myA is not itself const , overload resolution will favour the non- const overload.

That's life I'm afraid.

If you want the const version then you could use const_cast at the calling site, or even an implicit cast, to cast the myA to a const type:

const A& myA_const = myA;

and use myA_const where you want the const overload to be called.

I took the code fragments of the OP and made an MCVE which demonstrates what Bathsheba describes:

#include <iostream>
#include <vector>

class A {
  public:
    std::vector<int>& get()
    {
      std::cout << "A::get()" << std::endl;
      return myVector;
    }
    const std::vector<int>& get() const
    {
      std::cout << "A::get() const" << std::endl;
      return myVector;
    }

  private:
    std::vector<int> myVector;
};

int main()
{
  A myA;
  myA.get().push_back(1);
  for (const auto& v: myA.get()) { } // it involve not const get method
  // use const reference to instance
  std::cout << "use const reference to instance" << std::endl;
  { const A &myAC = myA;
    for (const auto& v: myAC.get()) { } // it involves const get method
  }
  return 0;
}

Output:

A::get()
A::get()
use const reference to instance
A::get() const

Tested on ideone .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM