Questions / Quant development, C++ ownership & memory

An alias can own more than it points at

Challenge, about 10 minutes. Question D127.

In C++17, all allocations succeed. What is printed after owner.reset()?

auto owner = std::make_shared<std::array<int, 2>>(std::array<int, 2>{9, 14});
std::shared_ptr<int> part(owner, &(*owner)[1]);
owner.reset();
std::cout << *part;

Answer it in the app It's free. You get hints, a second try if you miss, and a follow-up question.

Show the answer and worked solution

Answer: 14 value

  1. part shares ownership of the entire array with owner while storing the address of its second element. Resetting owner leaves part as an owner, so the array remains alive and *part is 14.

Interview shortcut. The aliasing constructor shares ownership of the whole array.

In the app this has a follow-up where one thing about the setup changes. Try the follow-up.

More c++ ownership & memory questions