LearnFrenzy
Sign in Take a free test

Smart Pointers · Predict the Output · Question 19

Raw pointers as non-owning observers Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 19 Back to Exercise

What is the output of the following C++ program on a 64-bit system?

main.cpp
#include <iostream>
#include <memory>
#include <string>
#include <vector>

struct City { std::string name; int pop; };

int main() {
    std::vector<std::unique_ptr<City>> owned;
    owned.push_back(std::make_unique<City>(City{"Pune", 7}));
    owned.push_back(std::make_unique<City>(City{"Delhi", 33}));
    owned.push_back(std::make_unique<City>(City{"Agra", 2}));

    City* biggest = nullptr;                        // observer: never deletes
    for (const auto& c : owned) if (!biggest || c->pop > biggest->pop) biggest = c.get();

    for (int i = 0; i < 100; ++i) owned.push_back(std::make_unique<City>(City{"x", 0}));   // vector reallocates…
    std::cout << biggest->name << ' ' << biggest->pop << ' ' << owned.size() << '\n';      // …but the City objects did not move
    return 0;
}
  • A Delhi 33 103 Correct
  • B Pune 7 103
  • C Delhi 33 3
  • D Undefined behaviour
Correct Answer: Option A

Reallocation moves the unique_ptrs, not the heap objects they own, so a raw pointer to a City stays valid. (A pointer to an element of a vector<City> would have dangled.)

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links