C++: Difference between revisions

695 bytes added ,  7 October 2019
no edit summary
No edit summary
Line 11: Line 11:
* <code>-std=c++17</code> for C++17 support
* <code>-std=c++17</code> for C++17 support
* <code>-O3</code> for level 3 optmizations
* <code>-O3</code> for level 3 optmizations
===Arrays===
In C++, you can use <code>std::vector</code> which gives you a resizable array.
This will allocate an array in the heap.<br>
[https://shendrick.net/Coding%20Tips/2015/03/15/cpparrayvsvector.html array vs vector]
If you need a static sized array, you can use <code>std::array</code>.<br>
This wrapper around C-style arrays gives us size information and allows the array to be passed around while keeping the array on the stack unlike <code>std::vector</code>
If you want to allocate a static array on the heap, you can do so as follows:
<syntaxhighlight lang="C++">
auto my_arr = std::make_shared<std::array<char,64>>();
</syntaxhighlight>
===Strings===
===Strings===
====String Interpolation====
====String Interpolation====
Line 72: Line 83:
====Smart Pointers====
====Smart Pointers====
[https://www.geeksforgeeks.org/auto_ptr-unique_ptr-shared_ptr-weak_ptr-2/ Smart Pointers]<br>
[https://www.geeksforgeeks.org/auto_ptr-unique_ptr-shared_ptr-weak_ptr-2/ Smart Pointers]<br>
There are 4 types of smart pointers
Smart pointers were added in C++11.<br>
There are 4 types of smart pointers:
* <code>auto_ptr</code> which is [https://stackoverflow.com/questions/3697686/why-is-auto-ptr-being-deprecated deprecated]
* <code>auto_ptr</code> which is [https://stackoverflow.com/questions/3697686/why-is-auto-ptr-being-deprecated deprecated]
* <code>unique_ptr</code>
* <code>unique_ptr</code>
Line 82: Line 94:


====Garbage Collection====
====Garbage Collection====
Starting from C++14, you should use smart pointers such as [https://en.cppreference.com/w/cpp/memory/shared_ptr <code>shared_ptr</code>] which have automatic garbage collection.<br>
Starting from C++11, you should use smart pointers such as [https://en.cppreference.com/w/cpp/memory/shared_ptr <code>shared_ptr</code>] which have automatic garbage collection.<br>
<br>
<br>
Traditional C++ does not have garbage collection.<br>
Traditional C++ does not have garbage collection.<br>