C++: Difference between revisions
(3 intermediate revisions by the same user not shown) | |||
Line 194: | Line 194: | ||
#include <fstream> | #include <fstream> | ||
#include <string> | #include <string> | ||
#include <string_view> | |||
std::string get_file_contents( | std::string get_file_contents(std::string_view filename) { | ||
{ | |||
std::ifstream in(filename, std::ios::in | std::ios::binary); | std::ifstream in(filename, std::ios::in | std::ios::binary); | ||
if (in.good()) | if (in.good()) { | ||
std::string contents; | std::string contents; | ||
in.seekg(0, std::ios::end); | in.seekg(0, std::ios::end); | ||
Line 266: | Line 265: | ||
Smart pointers were added in C++11.<br> | Smart pointers were added in C++11.<br> | ||
There are 3 types of smart pointers: | There are 3 types of smart pointers: | ||
* | * [https://en.cppreference.com/w/cpp/memory/unique_ptr <code>std::unique_ptr</code>] - one piece of code ''owns'' the memory at any given time.<br> | ||
* <code>std::shared_ptr</code> - the memory has multiple owners. | |||
* <code>std::weak_ptr</code> - a non-owning reference to a shared_ptr. | |||
In general, there should be one object owning an object using a <code>unique_ptr</code>. Whenever you pass the value around, other functions should receive the object as a reference making it clear that they do not have ownership of the object. Smart pointers are nullable and assignable similar to regular pointers. | |||
Prefer to use <code>make_unique</code> or <code>make_shared</code> which will only make one memory allocation for both the object and the pointer rather than two memory allocations.<br> | |||
You can call <code>my_ptr.reset(new Car())</code> to change the pointer or <code>my_ptr.reset()</code> to deallocate the object referenced by the pointer. | |||
Example: | Example: | ||
<syntaxhighlight lang="cpp"> | <syntaxhighlight lang="cpp"> |