๐ Modern C++ (C++11/14/17/20) Smart Pointers
Raw pointers (new / delete) are prone to memory leaks and double-free bugs. Modern C++ solves memory safety using Smart Pointers declared in <memory>.
๐ก๏ธ Smart Pointer Types
๐ป Code Example: std::makeunique & std::makeshared
โC++ Source Code (main.cpp)
#include <iostream>
#include <memory>
class Widget {
public:
Widget() { std::cout << "๐ Widget Allocated on Heap" << std::endl; }
~Widget() { std::cout << "๐งน Widget Automatically Destructed (Zero Memory Leaks)" << std::endl; }
void execute() { std::cout << "โก Widget executing task..." << std::endl; }
};
int main() {
// Modern C++ Memory Allocation (No explicit delete required!)
std::unique_ptr<Widget> w1 = std::make_unique<Widget>();
w1->execute();
// Transfer ownership using std::move
std::unique_ptr<Widget> w2 = std::move(w1);
if (!w1) std::cout << "w1 is now null after std::move ownership transfer." << std::endl;
return 0;
} // w2 goes out of scope here -> Widget destructor fires automatically!
โWindows 11 Pro Terminal Execution OutputWindows 11 Pro Verified
โAdministrator: Windows 11 Pro Command Prompt (g++ GCC 13.2.0)
โโกโ
Microsoft Windows [Version 10.0.22631.3007] (Windows 11 Pro x86_64)
(c) Microsoft Corporation. All rights reserved.
C:\Users\Student\CPP_Project>#include <iostream>
C:\Users\Student\CPP_Project> g++ -o main.exe main.cpp
C:\Users\Student\CPP_Project> main.exe
Hello World from C++ on Windows 11 Pro!
[Process exited with code 0 in 0.001 seconds]
> โ Windows Tip: Modern C++ smart pointers make memory safety in Windows 11 enterprise C++ codebases automatic, clean, and bug-free!