0

I have a function f that takes as argument a vector iterator. Inside this function, we need the address of the element that the iterator points to. For int-like values, this works fine. However, now I want to use this function on a std::vector<bool>, which doesn't compile. The following example should illustrate the situation:

#include <iostream>
#include <vector>

template <typename It>
void f(It it) {
    std::cout << "Your iterator starts at " << &(*it) << std::endl;
}

int main() {
    std::vector<int> v1(42, 1);
    f(v1.begin()); // <- fine

    std::vector<bool> v2(42, true);
    f(v2.begin()); // <- compilation error
}

When I compile this code with g++ -Wall test.cpp, the following error is reported:

test.cpp: In instantiation of ‘void f(It) [with It = std::_Bit_iterator]’:
test.cpp:19:17:   required from here
test.cpp:11:48: error: taking address of temporary [-fpermissive]
     std::cout << "Your iterator starts at " << &(*it) << std::endl;
                                                ^~~~~~

Removing the line f(v2.begin()); from the source lets the code compile.

I'd like to understand what's the difference between int and bool in this case that leads to the observed behavior? Why is bool temporary, whereas int is not?

Green绿色
  • 1,620
  • 1
  • 16
  • 43

0 Answers0