What’s the Time of Death?

Test your C++ programming skills by solving the given puzzle about temporary materialization and lifetime extension.

Puzzle code

Carefully read the code given below:

Press + to interact
#include <iostream>
struct MemoryArea
{
MemoryArea(int number) : number_(number) {}
~MemoryArea() { std::cout << "Freed memory area " << number_ << "\n"; }
int number_;
};
MemoryArea getMemory(int number) { return MemoryArea{number}; }
struct DataSource
{
DataSource(const MemoryArea &memoryArea)
: memoryArea_(memoryArea) {}
const MemoryArea &memoryArea_;
};
int main()
{
const auto &reference1 = getMemory(1);
std::cout << "Bound reference 1\n";
const auto &reference2 = getMemory(2).number_;
std::cout << "Bound reference 2\n";
const auto &reference3 = DataSource(getMemory(3));
std::cout << "Bound reference 3\n";
}

Your task: Guess the output

Try to guess the output of the above code. Attempt the following test to assess your understanding.

The possible console output lines are given below on the right side of the column. Place them in the correct sequence.

Drag and drop the cards in the blank spaces.


Let’s discuss this code and output together in the next lesson.

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.