Manage Dynamic Memory Safely

C++C++Beginner
Practice Now

Introduction

In this challenge, you are developing a small inventory management system for a local bookstore. The store needs a memory-efficient way to track book details without risking memory leaks. You will create a Book class using unique_ptr to dynamically manage book information, implement a constructor with parameters for title, author, and publication year, and add a method to display book details safely using smart pointer management.

This is a Challenge, which differs from a Guided Lab in that you need to try to complete the challenge task independently, rather than following the steps of a lab to learn. Challenges are usually a bit difficult. If you find it difficult, you can discuss with Labby or check the solution.

Manage Dynamic Memory Safely

You are developing a small inventory management system for a local bookstore. The store needs a memory-efficient way to track book details without risking memory leaks.

Tasks

  • Create a Book class using unique_ptr to dynamically manage book information
  • Implement a constructor that takes book title, author, and publication year
  • Add a method to display book information safely using smart pointer management
  • Demonstrate proper memory allocation and automatic cleanup

Requirements

  • Use unique_ptr for managing book object memory
  • Create the implementation in ~/project/book_tracker.cpp
  • Implement a constructor with parameters for title, author, and publication year
  • Include a displayInfo() method to print book details
  • Ensure no memory leaks occur during object creation and destruction

Examples

Compile and run the program to display book information:

g++ book_tracker.cpp -o book_tracker
./book_tracker

Example output:

Book Title: The Great Gatsby
Author: F. Scott Fitzgerald
Publication Year: 1925

Hints

  • Use std::unique_ptr for automatic memory management
  • Remember to initialize member variables in the constructor
  • Use std::move() when transferring ownership of unique pointers
  • Implement methods to safely access and display book information
✨ Check Solution and Practice

Summary

In summary, this challenge requires you to create a Book class that dynamically manages book information using unique_ptr. You will implement a constructor to initialize book details, such as title, author, and publication year, and add a method to safely display the book information. The goal is to demonstrate proper memory allocation and automatic cleanup, ensuring no memory leaks occur during object creation and destruction.