solti solti - 10 days ago 4
C++ Question

How to get address of objects in range based for loops?

I was trying to loop through my vector and get the address of the items stored in the vector. It works for other type of iterators (see below) but when I try to do this for

for(auto it :my_vec)
it throws error saying
error: no match for 'operator*' (operand type is 'my_class')


#include <iostream>
#include <vector>

class my_class{
int x;
public:
my_class(int x_):x(x_){}

};

std::vector<my_class> my_vec;

void fill_vec(size_t size){

for(int i = 0; i < size; i++){
my_vec.push_back(my_class(i));
}

}

int main(){

size_t size = 10;

fill_vec(size);

for(auto it :my_vec){
std::cout << &it << std::endl;
std::cout << &(*it) << std::endl;
}

std::cout << "-----------" << std::endl;

for(auto it = my_vec.begin(); it != my_vec.end(); it++){
std::cout << &(*it) << std::endl;
}

std::cout << "-----------" << std::endl;

for(size_t i = 0; i < my_vec.size(); i++){
std::cout << &my_vec[i] << std::endl;
}

return 0;
}

Answer

How to get address of objects in range based for loops?

In the same way as you get the address of objects anywhere else: Using the addressof operator (operator&).

It works for other type of iterators (see below) but when I try to do this for for(auto it :my_vec) it throws error saying error: no match for 'operator*' (operand type is 'my_class')

Range based for loop doesn't give you an iterator. It gives you an object. In this case you used auto, so it gives you a my_class instance (because that happens to be the value_type of the container) that is the copy of the object in the vector. my_class doesn't have overload for operator* (the dereference operator), so the line that you tried (that contains *it) didn't work and the compiler describes the problem for you.


So, std::cout << &it << std::endl; is correct, but it gives you the address of the copy, not the object in the vector. Since you probably want the address of the object in the vector, you should be using auto& or my_class& to get a reference instead. When you use a reference as an operand to the addressof operator, you get the address of the referenced object.

Comments