C++: Difference between revisions

Line 142: Line 142:
Example:
Example:
<syntaxhighlight lang="cpp">
<syntaxhighlight lang="cpp">
// Block-scope car
Car my_car;
// Old C++
Car *my_car = new Car();
// Must call delete my_car; to avoid memory leaks.
// Using unique ptr
std::unique_ptr<Car> my_car(new Car());
std::unique_ptr<Car> my_car(new Car());
// Or starting from C++14
// Or starting from C++14
auto my_car = std::make_unique<Car>();
auto my_car = std::make_unique<Car>();
</syntaxhighlight>
</syntaxhighlight>
Note: If the object you need is not very large, you can consider just including it as part of your class (or leaving it on the stack) rather than use pointers.


====Garbage Collection====
====Garbage Collection====