简体   繁体   中英

When "for each" loop returns nullptr for a item?

I watched CppCon "Writing Good C++14... By Default" by Herb Sutter and on one of the slides was following piece of code:

auto p = make_shared<circle>(42);
auto v = load_shapes();
for(auto& s: v) {
  if(s && *s == *p) {
    cout << *s << "is a match\n";
  }
}

My question is: why there is a

if(s && *s == *p)

check?

How can reference variable initialized by for each loop be nullptr ? Loop iterates over items, so in which case nullptr value can be assigned ?

EDIT : My point of interest is what is this check for:

if(s)

When s is obtained by "for each", how it can be null?

Assume the following definitions.

struct circle {
    circle(int r) :radius(r) {}
    int radius;

    bool operator==(circle rhs) const {
        return radius == rhs.radius;
    }
};

std::vector<circle*> load_shapes() {
    std::vector<circle*> vec;
    for (int i = 0; i < 10; ++i)
        vec.push_back(nullptr);
    return vec;
}

With that, I can now insert the example code into a main function:

int main() {
    using namespace std;
    auto p = make_shared<circle>(42);
    auto v = load_shapes();
    for(auto& s: v) {
      if(s && *s == *p) {
        cout << *s << "is a match\n";
      }
    }
}

With that definition for load_shapes , v (in main) is of type std::vector<circle*> , it has 10 elements, all of them null pointers. So in the for loop, s is of type circle*& (reference to pointer to circle). And in each iteration, the pointer it refers to is a null pointer. That's what the if statement is checking for.

Note that there are of course other possible definitions. For example, load_shapes could return std::vector<std::shared_ptr<shape>> , where shape is a base class of circle (and I suspect that is exactly what the slide author had in mind).

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