https://en.cppreference.com/bookwiki/api.php?action=feedcontributions&user=Cubbi&feedformat=atomcppreference.com - User contributions [en]2024-03-28T20:46:41ZUser contributionsMediaWiki 1.21.2https://en.cppreference.com/book/intro/typesintro/types2020-07-06T16:03:50Z<p>Cubbi: title/warning</p>
<hr />
<div>{{title|types}}<br />
Computers represent values in sequence of bits, grouped into bytes. Every bit can be one or zero. One byte is 8 bits. Byte is the smallest addressable area of the main memory.<br />
<br />
Fundamental types in C++:<br />
* Boolean (logical): {{c|bool}}<br />
* Integer numbers: {{c|char}}, {{c|int}}, {{c|uint16_t}}, {{c|size_t}}, ...<br />
* Floating point numbers: {{c|float}}, {{c|double}}, {{c|long double}}<br />
<br />
Compound types in C++<br />
* Pointers: Variables capable to hold the address of other variables.<br />
* References: They are similar to pointers with some (useful) restrictions.<br />
* Arrays: Continuous sequence of elements in memory of the same type.<br />
* Structures: A grouping of named data members.<br />
<br />
Other compound types in C++ which we will not detail in this introductory section:<br />
* Classes: An abstract data type with the capability to protect its own type invariant properties. (1)<br />
* Functions, lambdas (C++11): Functions also have types and their pointer can be passed around.<br />
* Template structures, classes and functions: Incomplete types which become particular types with specific compile time parameters where needed.<br />
<br />
(1) Technically structures and classes are the same, not counting the default visibility of their members. The above definitions rather refer to their common role of usage.<br />
<br />
=Fundamental types=<br />
<br />
==Boolean==<br />
<br />
The type {{c|bool}} is designed to hold a logical value. One bit would be enough to store it, but it takes more space because of efficient moving and copying. Its possible values are {{c|true}} and {{c|false}}. Comparisons are low precedence operators which are evaluated to {{c|bool}}, like in this snippet:<br />
{{source|<br />
if(x{{==}}42){ /* do something */ }<br />
}}<br />
You can assign the value of a comparison to a boolean:<br />
{{source|<br />
bool b {{=}} (x < 43);<br />
}}<br />
<br />
Common operators for the {{c|bool}} type are logical and ({{c|&&}}), logical or ({{c|{{!!}}}}) and logical not ({{c|!}}). Logical exclusive or can be expressed with the not-equals comparison like {{c|a !{{=}} b}}.<br />
<br />
==Integers==<br />
<br />
===Concept===<br />
<br />
Integer numbers are represented using the binary numeral system, where every bit is used to store one base-2 digit. There are signed and unsigned types. For signed types one bit is used to store the sign of the number.<br />
<br />
We have basic operations like addition {{c|+}}, subtraction {{c|-}}, multiplication {{c|*}}, division {{c|/}} and modulo {{c|%}}. We can also use binary operations like binary and {{c|&}}, or {{c|{{!}}}}, exclusive-or {{c|^}} and not {{c|~}}. In explanatory text I will use the ^ sign for exponentiation and {{c|^}} sign (gray background) for binary exclusive-or.<br />
<br />
Note that if you want to store the computational result in the left hand operand you can simply write {{c|x +{{=}} 3}} instead of {{c|x {{=}} x + 3}}.<br />
<br />
===Reference teaser===<br />
<br />
Integer types can be prefixed with the {{c|signed}} or the {{c|unsigned}} keyword. Generally the signed version is the default, but it can be compiler (or compilation option) dependent. Minimum and maximum values for unsigned types are 0 and 2^b-1, for signed types they are -2^(b-1) and 2^(b-1)-1 where b is the number of bits used to represent the number.<br />
<br />
{{c|char}}: At least one byte long. Most of the time it is exactly one byte, but you should not rely on that. Can store numbers from -128 to 127 (or from 0 to 255). It is also used to store characters according to the ASCII table, where the numerical value 65 means capital 'A'.<br />
<br />
{{c|short [int]}}, {{c|int}}, {{c|long [int]}}, {{c|long long [int]}} (since c++11): Larger integer types. At least they are 2, 2, 4 and 8 bytes long. Usually they are 2, 4, 4 and 8 bytes. On 64 bit systems {{c|long}} is often 8 bytes.<br />
<br />
The {{c|int}} keyword can be used after {{c|short}}, {{c|long}} and {{c|long long}} where it has no additional meaning, or it can stand alone when it means at least 16 bits. All of the above can be prefixed with {{c|unsigned}} or {{c|signed}}.<br />
<br />
===Fixed size integer types===<br />
<br />
Fixed size integer types can be found in the cstdint header (or stdint.h before C++11 or in C). These types are {{c|uint8_t}}, {{c|int8_t}}, ..., and {{c|int64_t}}.<br />
<br />
===Other integer types===<br />
<br />
{{c|size_t}}: A type which is used to represent container sizes of arrays or standard template containers. You can get detailed information on that in chapters about arrays and standard template containers.<br />
<br />
{{c|ptrdiff_t}}: Type for the difference of two pointers. You can get detailed description about that in chapters about pointers.<br />
<br />
And there are some other similarly abstractly named integer types. We will get to now them as we meet them.<br />
<br />
===Example program with booleans and integers===<br />
<br />
{{source|<br />
#include <iostream> // For standard input, output and error (std::cin, std::cout and std::cerr)<br />
<br />
int main()<br />
{<br />
long a,b; // We create 'a' and 'b' without initialization. Their value is undefined yet.<br />
std::cout << "Operations between integer numbers" << "\n"; // std::endl is end of line<br />
std::cout << "Operand 'a': "; std::cin >> a; // Read into 'a'<br />
std::cout << "Operand 'b': "; std::cin >> b; // Read into 'b'<br />
std::cout << "a + b {{=}} " << (a+b) << "\n"; // addition<br />
std::cout << "a - b {{=}} " << (a-b) << "\n"; // subtraction<br />
std::cout << "a * b {{=}} " << (a*b) << "\n"; // multiplication<br />
if(b!{{=}}0) // divisor is not zero:<br />
{<br />
std::cout << "a / b {{=}} " << (a/b) << "\n"; // division<br />
std::cout << "a % b {{=}} " << (a%b) << "\n"; // modulo<br />
}<br />
else // divisor is zero:<br />
{<br />
std::cout << "a / b is mathematically undefined." << "\n";<br />
std::cout << "a % b is mathematically undefined." << "\n";<br />
}<br />
bool aParity {{=}} (a % 2); // Parity of 'a' as logical value<br />
bool bParity {{=}} (b % 2); // Parity of 'b' as logical value<br />
std::cout << a << " is " << (aParity?"odd":"even") << "\n"; // See trinary operator '?:'<br />
std::cout << b << " is " << (bParity?"odd":"even") << "\n"; // See trinary operator '?:'<br />
std::cout << "Bytes used to hold a boolean value in this environment: " << sizeof(bool) << "\n";<br />
std::cout << "Size of int in this environment: " << sizeof(int) << "\n";<br />
return 0; // For the shell zero is success<br />
}<br />
<br />
}}<br />
<br />
In {{c|bool aParity {{=}} (a % 2);}} we used casting (converting) from {{c|long}} to {{c|bool}} as {{c|(a % 2)}}'s type is {{c|long}}. When we cast integers to boolean everything that is non-zero counts as {{c|true}}, and zero counts as {{c|false}}.<br />
<br />
The {{c|sizeof()}} operator (not function, as it is a notation which is calculated at compile time) can tell you the storage size of a type in bytes. You can use any expression as parameter, like {{c|sizeof(a)}}.<br />
<br />
==Floating point numbers==<br />
<br />
{{c|float}}: Single precision floating point number with 32 bits as specified in IEEE-754<br />
<br />
{{c|double}}: Double precision floating point number with 64 bits as specified in IEEE-754.<br />
<br />
{{c|long double}}: Extended precision floating point number. Usually 80 bits long.<br />
<br />
Example program with floating point numbers:<br />
{{source|<br />
#include <iostream> // For standard input, output and error (std::cin, std::cout and std::cerr)<br />
#include <cmath> // Mathematical utilities. Wee need it for square root: sqrt()<br />
<br />
int main()<br />
{<br />
std::cout << "We will calculate the perimeter and the area of a triangle." << "\n";<br />
// std::endl is end of line<br />
double a,b,c; // Variables to hold the sides of the triangle. Their value is undefined yet.<br />
std::cout << "a {{=}} "; std::cin >> a; // Read into 'a'<br />
std::cout << "b {{=}} "; std::cin >> b; // Read into 'b'<br />
std::cout << "c {{=}} "; std::cin >> c; // Read into 'c'<br />
double P {{=}} a + b + c; // Perimeter<br />
double s {{=}} P / 2; // Half of perimeter.<br />
// No side can be larger than that. Also needed later.<br />
if(a>s {{!!}} b>s {{!!}} c>s {{!!}} a<0 {{!!}} b<0 {{!!}} c<0) // No side can be negative either<br />
{<br />
cerr << "Invalid triangle." << "\n";<br />
return -1; // For the shell non-zero is error<br />
}<br />
double A {{=}} sqrt(s*(s-a)*(s-b)*(s-c)); // Heron's formula.<br />
std::cout << "Perimeter is " << P << "\n"; // Display perimeter<br />
std::cout << "Area is " << A << "\n"; // Display area<br />
return 0; // For the shell zero is success<br />
}<br />
}}<br />
<br />
=Compound types=<br />
<br />
==Pointer==<br />
<br />
Pointers are special values which hold memory addresses. When you dereference a pointer you can access a value. Pointers can be set as addresses of already existing values or can be set to newly allocated values.<br />
<br />
They can also be null (numerical {{c|0}} or {{c|nullptr}} since C++11). If you use a pointer as boolean it evaluates to {{c|true}} if it is not null, to {{c|false}} otherwise. Null used to represent the state when the pointer is not set to any particular value.<br />
<br />
{{source|<br />
int x {{=}} 17; // Integer typed value with the name 'x' and initial value 17<br />
int *p1; // 'int *' is a type: pointer to integer. The name of the variable is p1<br />
p1 {{=}} nullptr; // Or '0' before C++11 or in C.<br />
int *p2 {{=}} &x; // The starting value if 'p2' is the address of 'x'.<br />
*p2 +{{=}} 10; // In this figure the '*' is an unary operator (not a part of a type expression).<br />
// It means dereferencing. If you dereference the 'p' pointer you get to<br />
// the x value. Then we increment this value with 10 using the '+{{=}}' operator.<br />
std::cout << x << std::endl; // Prints out 27<br />
}}<br />
<br />
Let's see another program where a function takes a pointer as argument.<br />
<br />
{{source|<br />
#include <iostream><br />
<br />
void increment_v1(int v) // This function expects an integer value as parameter, returns nothing<br />
{<br />
v +{{=}} 10; // This will not change the value in the caller context as parameters count as<br />
// function parameters counts as local variables inside the functions.<br />
}<br />
<br />
void increment_v2(int *pV) // This function expects a pointer to integer, returns nothing.<br />
{<br />
*pV +{{=}} 10; // This will change something that is pointed by 'pV'.<br />
}<br />
<br />
int main()<br />
{<br />
int a {{=}} 150, b {{=}} 200;<br />
increment_v1(a); // 'a' remains unchanged<br />
std::cout << a << "\n"; // Outputs '150'<br />
increment_v2(&a); // This passes the address of our 'a' to the other function, so it<br />
std::cout << a << "\n"; // can change its value. Outputs '160'<br />
increment_v2(&b); // We can use the same function with a different pointer.<br />
std::cout << b << "\n"; // Outputs '210'<br />
return 0; // OK<br />
}<br />
}}<br />
<br />
Pointers also have arithmetic possibilities, but these have meaning only in the context of arrays. We will talk about it a little bit later.<br />
<br />
===Dangers of pointers===<br />
<br />
You must never dereference a null pointer. That will cause undefined behavior, in most cases causes the program to crash with Access violation (Windows) or Segmentation fault (Linux), etc... We can expect similar results if we try do dereference an uninitialized pointer.<br />
<br />
==Reference==<br />
<br />
As a first approach we can say that references are pointers with the following differences:<br />
* A reference must be initialized when it is created.<br />
* A reference cannot be changed.<br />
* The dereferencing of it is automatic, there is no notation for it. Explicit dereferencing is error.<br />
* We take the address of the pointed implicitly when it is initialized. No {{c|&}} needed. (In fact it is an error if you place it.)<br />
<br />
Example and explanation<br />
<br />
{{source|<br />
int x {{=}} 17; // OK<br />
int &r1; // Error. A reference must be initialized.<br />
r1 {{=}} nullptr; // Error: A reference cannot be changed<br />
int &r2 {{=}} &x; // Error: We don't use '&' of pointed value when initializing<br />
int &r3 {{=}} x; // OK. The 'r3' now points to x;<br />
*r3 +{{=}} 10; // Error: Explicit dereferencing is error<br />
r3 +{{=}} 10; // OK! The 'x' is increased by 10.<br />
std::cout << x << std::endl; // Prints out 27<br />
std::cout << r3 << std::endl; // Prints out 27. Dereferencing is automatic again.<br />
}}<br />
<br />
References give smoother outfit to the code once when understood. If you await a reference in a parameter list then you formally express that that parameter is absolutely needed for the operation. While it is easily possible to give null pointer as argument where a pointer is expected.<br />
<br />
Let's see how it cleans up some clutter in our code with the incrementing functions. (We omit increment_v1 as it has no explanatory value for us anymore.)<br />
<br />
{{source|<br />
#include <iostream><br />
<br />
void increment_v2(int &v) // Take argument by reference<br />
{<br />
v +{{=}} 10; // Dereferencing is automatic. We increase the pointed value by 10.<br />
}<br />
<br />
int main()<br />
{<br />
int a {{=}} 150, b {{=}} 200;<br />
increment_v2(a); // We don't take address explicitly...<br />
std::cout << a << "\n"; // Outputs 160.<br />
increment_v2(b); // ..., it is taken implicitly.<br />
std::cout << b << "\n"; // Outputs 210.<br />
return 0;<br />
}<br />
}}<br />
<br />
Sometimes references do not manifest in reality as a pointer like phenomenon, they just appear as aliases. If we have an {{c|int a;}} and an {{c|int &b {{=}} a;}} then it is possible that the generated machine code will be the same where you mention 'a' and 'b'. That does not lead to any difference in the computational result of the program but may save some memory and CPU time.<br />
<br />
==Array==<br />
<br />
An array is a sequence of same type values in memory. Arrays can be defined with fixed size, or allocated at runtime. We expect the reader to know about loops (for, while, etc...). Arrays can be used to store characters, numbers, strings, structures or any other type of values including arrays.<br />
<br />
Single dimensional arrays are useful for creating sequences of chess moves, characters, records.<br />
<br />
If you have array typed values in an array then you have a so called multi dimensional array which can be used for storing board-like information like an elevation map, a chess board and so on.<br />
<br />
Basic features of arrays include:<br />
* Defining a fixed size array: {{c|int a[10];}}<br />
** Defining array with runtime size (C++11, C99): {{c|int n; std::cin >> n; int a2[n];}}<br />
* Creating an array dynamically on heap {{c|int n; std::cin >> n; int *a3 {{=}} new int[n];}}<br />
* Accessing array members: {{c|a[2] {{=}} a[0] + a[1];}}<br />
* Deleting a dynamically created array {{c|delete[] a3;}}<br />
<br />
Array elements are indexed from zero to size minus one.<br />
<br />
{{source|<br />
#include <iostream><br />
<br />
int main()<br />
{<br />
std::cout << "Number sequence reverser tool" << "\n"; // Banner for program<br />
size_t n; // To store the number of elements<br />
std::cout << "Number of elements: "; std::cin >> n; // Read into 'n'<br />
int *numbers {{=}} new int[n]; // Allocate array dynamically with size 'n'<br />
for(size_t i{{=}}0; i<n; ++i) // Loop from 0 to n-1 using i<br />
{<br />
std::cout << "Number #" << (i+1) << ": "; // Print human indexing when asking for number<br />
std::cin >> numbers[i]; // Reads into 'numbers[i]'<br />
}<br />
// This will reverse the numbers in the array<br />
for(size_t i{{=}}0; i<n/2; ++i) // Loop to half. Limit has been chosen carefully.<br />
{<br />
int tmp {{=}} numbers[i]; // This is a three step swap of<br />
numbers[i] {{=}} numbers[n-1-i]; // numbers[i] and numbers[n-1-i]<br />
numbers[n-i-1] {{=}} tmp; // using a temporary variable tmp.<br />
}<br />
std::cout << "Numbers in reverse order:" << "\n"; // Banner for result<br />
for(size_t i{{=}}0; i<n; ++i) // Loop from 0 to n-1 using i<br />
{<br />
if(i>0) // We don't need comma before the first element,<br />
std::cout << ", "; // but after that we do.<br />
std::cout << numbers[i]; // Prints 'numbers[i]'<br />
}<br />
std::cout << "\n"; // Prints line feed after last number.<br />
delete[] numbers; // Deallocates array. Does not make 'numbers' to be 0 (or nullptr)<br />
// Dereferencing it after this line is error.<br />
return 0;<br />
}<br />
}}<br />
<br />
(To be continued... Example for multi dimensional array)<br />
<br />
==Arrays and pointers==<br />
<br />
(In progess) Pointers, arrays, structs, (classes, template classes ??).</div>Cubbihttps://en.cppreference.com/book/intro/vectorintro/vector2020-07-06T16:02:48Z<p>Cubbi: title/warning</p>
<hr />
<div>{{title|vector}}<br />
== Vector ==<br />
<br />
The vector container, declared in ''<vector>'', allows for keeping a variable sequence of elements of arbitrary data type. These are its essential properties:<br />
<br />
* The data type of the elements in the vector can be defined as a template argument:<br />
<br />
{{source|1=<br />
std::vector<int> v1; // a vector of integers<br />
std::vector<int*> v2; // a vector of pointers to integer(s)<br />
std::vector<std::string> v3; // a vector of strings<br />
std::vector<std::vector<int> > v3; // a vector of vectors of int's<br />
}}<br />
<br />
* Vectors have a variable number of elements, which can be inserted, removed and accessed in runtime:<br />
<br />
{{source|1=<br />
using namespace std;<br />
vector<int> vec = {1,2,3}; // you can initialize vectors with an initializer list since C++11<br />
cout << vec.size() << endl; // will print 3 <br />
vec.push_back(5); // insert 5 at the end of the vector<br />
cout << vec[3] << endl; // will print 5 <br />
vec[1] = 10; // change the second element to 10<br />
cout << vec.front() << endl; // first element, will print 1 <br />
cout << vec.size() << endl; // will print 4 <br />
}}<br />
<br />
* Elements in a vector are contiguous like in an array, so it provides fast read/write operations on any element. Internally, these are kept in a dynamically allocated array of larger (or equal) size, so that it can grow larger. If this array is full before inserting another element, the vector will relocate every single element currently in it into a larger array. This means two things: there is no theoretical limit on the number of elements of a vector, but inserting many elements at a time will force a capacity increase of the vector, which can become a heavy operation. You can use the capacity() member function in order to find to what size can the vector grow to without an expansion.<br />
<br />
{{source|1=<br />
vector<int> vec = {0, 3, 4, 6};<br />
cout << vec.capacity() << endl; // will print a number greater or equal to 4<br />
vec.reserve(10); // you can also force an expansion of the vector<br />
cout << vec.capacity() << endl; // will print 10<br />
vec.shrink_to_fit(); // since C++11, you can contract the vector to the minimum capacity needed<br />
cout << vec.capacity() << endl; // will print 4<br />
}}<br />
<br />
* Access to an element out of the vector's range (using a bad index for example) will not necessarily cause an error with the array suffix operator[]. On the other hand, the at() function includes bounds checking.<br />
<br />
{{source|1=<br />
vector<float> vec (3, 2.0f); // initialize a vector with 3 elements set to 2.0f<br />
float myfloat1 = vec[2]; // OK<br />
float myfloat2 = vec[3]; // undefined behavior!<br />
vec[6] = myfloat1; // undefined behavior!<br />
float myfloat3 = vec.at(1); // OK<br />
vec.at(6) = 1.0f; // will throw std::out_of_range exception!<br />
}}<br />
<br />
* Like any other container, they can be iterated using a standard iterator or a for-each statement:<br />
<br />
{{source|1=<br />
vector<int> vec = {5, 3, 1};<br />
for (auto it = begin(vec) ; it != end(vec) ; it++) {<br />
cout << *it << endl; // print each element<br />
}<br />
<br />
for (int& e : vec) {<br />
e++; // increment each element by one<br />
}<br />
}}<br />
<br />
Vectors are preferred when keeping a sequence of elements for random access due to its ''O(1)'' complexity. Once created, it can be accessed in a similar fashion to an array. If the needed capacity for the vector is unknown, it can still be used without major issues, thanks to the various element insertion and removal functions available.</div>Cubbihttps://en.cppreference.com/book/intro/range_forintro/range for2020-07-06T16:02:27Z<p>Cubbi: title/warning</p>
<hr />
<div>{{title|range for}}<br />
===The range-based {{tt|for}} statement===<br />
<br />
The range-based {{tt|for}} statement is a simpler and safer way to loop over the contents of a container or array.<br />
<br />
It looks like this:<br />
<br />
{{source|1=<br />
for (/* variable declaration */ : /* container or array */) {<br />
// statements<br />
}<br />
}}<br />
<br />
Which, for a container, expands to:<br />
<br />
{{source|1=<br />
for (auto p = container.begin(); p != container.end(); ++p) {<br />
/* variable declaration */ = *p;<br />
// statements<br />
}<br />
}}<br />
<br />
For an array it expands to:<br />
<br />
{{source|1=<br />
for (int n = 0; n != sizeof(array); ++n) {<br />
/* variable declaration */ = array[n];<br />
// statements<br />
}<br />
}}<br />
<br />
Normally you would use a variable declaration with {{c|auto}}, or possibly {{c|const auto&}}:<br />
<br />
{{source|1=<br />
for (auto item : items) {<br />
// statements<br />
}<br />
}}<br />
<br />
If you don't use {{c|auto}}, the values in the container or array must be convertible to whatever type you use.<br />
<br />
For example:<br />
<br />
{{example<br />
|code=<br />
#include <iostream><br />
#include <string><br />
#include <vector><br />
<br />
int main()<br />
{<br />
std::vector<std::string> doctors = { "Strange", "Octopus", "Who" };<br />
<br />
// You could use "std::string" instead of "auto"<br />
for (auto const& doc : doctors) {<br />
std::cout << "Paging Dr. " << doc << '\n';<br />
}<br />
}<br />
|output=<br />
Paging Dr. Strange<br />
Paging Dr. Octopus<br />
Paging Dr. Who<br />
}}<br />
<br />
If you use a non-{{c|const}} reference, you can change the values in the container or array within the loop:<br />
<br />
For example:<br />
<br />
{{example<br />
|code=<br />
#include <iostream><br />
<br />
int main()<br />
{<br />
int numbers[] = { 1, 2, 3, 4 };<br />
<br />
// Print numbers<br />
for (auto n : numbers)<br />
std::cout << n << ' ';<br />
<br />
// Double each number<br />
for (auto& n : numbers)<br />
n *= 2;<br />
<br />
std::cout << '\n';<br />
<br />
// Print numbers<br />
for (auto n : numbers)<br />
std::cout << n << ' ';<br />
}<br />
|output=<br />
1 2 3 4 <br />
2 4 6 8<br />
}}<br />
<br />
The range-based {{tt|for}} statement is not only easier to write, it is safer.<br />
You cannot accidently go past the end of a container or array, or make other mistakes like this:<br />
<br />
{{source|1=<br />
std::vector<int> c1 = { 1, 2, 3 };<br />
std::vector<int> c2 = { 4, 5, 6 };<br />
<br />
// Mixing the begin/end from c1 and c2 by accident!<br />
// This causes undefined behaviour!<br />
for (auto p = c1.begin(); p != c2.end(); ++p) {<br />
std::cout << *p << '\n';<br />
}<br />
}}<br />
<br />
On the other hand, the range-based {{tt|for}} statement is more limited.<br />
You can't start half-way through the sequence, and you can't advance by more than one item at a time.<br />
You can keep track of where you are in the sequence, but it requires an extra variable.<br />
(And of course, you can always end before the end of the sequence with a {{c|break}} statement.)</div>Cubbihttps://en.cppreference.com/book/intro/encapsulationintro/encapsulation2020-07-06T16:00:45Z<p>Cubbi: missing title/warning</p>
<hr />
<div>{{title|encapsulation}}<br />
Encapsulation is one of the most fundumental and valuable features of object oriented programming in general and c++ in particular.<br />
The ability to hide the details from the user of your code and encapsulate everything under a clear interface is a great advantage.<br><br />
example:<br><br />
class square{<br />
public:<br />
rectangle( int top_left, int top_right, int buttom_left, buttom_right )<br />
private:<br />
std::pair<int, int> top;<br />
std::pair<int, int> buttom;<br />
};<br />
<br />
In this example the interface calls for 4 integers and the implementation uses 2 pairs.<br />
The implementation along with the activities (not shown here) on the variables is encapsulated within the class.</div>Cubbihttps://en.cppreference.com/book/intro/exceptionsintro/exceptions2020-07-06T15:59:47Z<p>Cubbi: missing tittle/warning</p>
<hr />
<div>{{title|exceptions}}<br />
An exception is a construct for reporting an unexpected occurrence during the execution of a module within a software system. An exception may the result of a fault in the calling module, a fault in the called module, or it may the result of a fault in the environment.<br />
<br />
== A Basic Theory of Exceptions ==<br />
<br />
Formally, an exception occurs as the result of the invocation of a function or method. Each function or method is described by a set of preconditions, a set of invariants, and a set of post conditions. A given invocation that ensures a particular set of preconditions, can reasonably expect that the invocation completes with a given set of invariants holding true, and a set of postconditions resulting. <br />
<br />
<br />
In other words, if the preconditions have been met, but the called module cannot preserve the invariants or ensure the postconditions, and exception should be thrown.<br />
<br />
<br />
Ok, that makes my head hurt! What does it really mean? It means if for a given method or function call, that if I have done all the correct steps prior to making that call, and the system state is correct, then I can reasonably expect the predicted result. When the preconditions have been met (you've done what you were supposed to do) and the system state cannot be maintained (the invariants) or the postconditions (predictable result) cannot be met, an exception should be thrown. Some exceptions may be recoverable, others may require that the module and possibly the entire system be shutdown until the underlying cause is repaired.<br />
<br />
== Exception Basics ==<br />
<br />
The following contrived example provides a complete example for the usage of exceptions.<br />
<br />
{{source|1=<br />
// todo: add example<br />
}}<br />
<br />
== Exceptions are Not Errors, Errors are Not Exceptions ==<br />
<br />
In many frameworks where exceptions are defined and used, they are used as a substitute for errors. An error is a predictable occurrence in the operation of a module. Overuse of exceptions in C++ can result in performance degradations as the result of the overhead necessary to unwind the execution state from where the exception was thrown to the nearest {{c| try { } catch( ... ) { } }} block.</div>Cubbihttps://en.cppreference.com/book/intro/smart_pointersintro/smart pointers2020-07-06T15:58:21Z<p>Cubbi: somehow this didn't have a title (and someone linked to it on SO)</p>
<hr />
<div>{{title|smart pointers}}<br />
Smart pointers are used to make sure that an object is deleted if it is no longer used (referenced).<br />
<br />
See this simple example:<br />
<br />
{{example<br />
|code=<br />
void my_func()<br />
{<br />
int* valuePtr = new int(15);<br />
int x = 45;<br />
// ...<br />
if (x == 45)<br />
return; // here we have a memory leak, valuePtr is not deleted<br />
// ...<br />
delete valuePtr;<br />
}<br />
<br />
int main()<br />
{<br />
}<br />
<br />
}}<br />
<br />
The same example using the {{tt|unique_ptr<>}} template:<br />
<br />
{{example<br />
|code=<br />
#include <memory><br />
<br />
void my_func()<br />
{<br />
std::unique_ptr<int> valuePtr(new int(15));<br />
int x = 45;<br />
// ...<br />
if (x == 45)<br />
return; // no memory leak anymore!<br />
// ...<br />
}<br />
<br />
int main()<br />
{<br />
}<br />
<br />
}}<br />
<br />
The {{tt|unique_ptr<>}} template holds a pointer to an object and deletes this object when the {{tt|unique_ptr<>}} object is deleted. So, in the example above, it does not matter if the function scope is left through the return statement, at the end of the function or even through an exception: The {{tt|unique_ptr<>}} destructor is always called and therefore the object ({{tt|int}} in the example) always deleted.<br />
<br />
The following three smart pointer templates are available:<br />
<br />
==unique_ptr==<br />
<br />
As the name implies, make sure that only exactly one copy of an object exists. Can be used as in the example above for handling dynamically allocated objects in a restricted scope.<br />
<br />
A unique pointer can be initialized with a pointer upon creation<br />
<br />
{{source|1=std::unique_ptr<int> valuePtr(new int(47));}}<br />
<br />
or it can be created without a pointer and assigned one later<br />
<br />
{{source|1=std::unique_ptr<int> valuePtr; <br />
valuePtr.reset(new int(47));<br />
}}<br />
<br />
Note: In this second case, if the {{tt|unique_ptr<>}} already holds a pointer to an existing object, this object is deleted first and then the new pointer stored.<br />
<br />
Afterwards, an object managed by a {{tt|unique_ptr<>}} can be accessed just like when you would use a raw pointer:<br />
<br />
{{source|1=std::unique_ptr<std::string> strPtr(new std::string); strPtr->assign("Hello world");}}<br />
<br />
The {{tt|unique_ptr<>}} does not support copying. If you try to copy a {{tt|unique_ptr<>}}, you'll get compiler errors. However, it supports move semantics, where the pointer is moved from one {{tt|unique_ptr<>}} to another, which invalidates the first {{tt|unique_ptr<>}}.<br />
<br />
See the following example:<br />
<br />
{{example<br />
|code=<br />
#include <iostream><br />
#include <memory><br />
#include <utility><br />
<br />
int main()<br />
{<br />
std::unique_ptr<int> valuePtr(new int(15));<br />
std::unique_ptr<int> valuePtrNow(std::move(valuePtr));<br />
<br />
std::cout << "valuePtrNow = " << *valuePtrNow << '\n';<br />
std::cout << "Has valuePtr an associated object? "<br />
<< std::boolalpha<br />
<< static_cast<bool>(valuePtr) << '\n';<br />
}<br />
|output=<br />
valuePtrNow = 15<br />
Has valuePtr an associated object? false<br />
<br />
}}<br />
<br />
==shared_ptr==<br />
The shared_pointer is a reference counting smart pointer that can be used to store and pass a reference beyond the scope of a function. This is particularly useful in the context of OOP, to store a pointer as a member variable and return it to access the referenced value outside the scope of the class. Consider the following example:<br />
<br />
{{example<br />
|code=<br />
#include <memory><br />
<br />
class Foo<br />
{<br />
public void doSomething();<br />
};<br />
<br />
class Bar<br />
{<br />
private:<br />
std::shared_ptr<Foo> pFoo;<br />
public:<br />
Bar()<br />
{<br />
pFoo = std::shared_ptr<Foo>(new Foo());<br />
}<br />
<br />
std::shared_ptr<Foo> getFoo()<br />
{<br />
return pFoo;<br />
}<br />
};<br />
<br />
}}<br />
<br />
When an object of the Bar class is created it creates a new object of the Foo class, which is stored in pFoo. To Access pFoo we can call Bar::getFoo which returns a std::shared_ptr to the Foo object created in the Bar constructor. Internally, a copy of the std::shared_ptr object is created and returned. The copy constructor of std::shared_ptr copies the internal pointer to the Foo object and increases the reference count. This would, for example, happen in the following example: <br />
<br />
{{example<br />
|code=<br />
<br />
void SomeAction()<br />
{<br />
Bar* pBar = new Bar(); //with the Bar object, a new Foo is created and stored<br />
//reference counter = 1<br />
<br />
std::shared_ptr<Foo> pFoo = pBar->getFoo(); //a copy of the shared pointer is created<br />
//reference counter = 2<br />
<br />
pFoo->doSomething(); <br />
<br />
delete pBar; //with pBar the private pFoo is destroyed<br />
//reference counter = 1<br />
<br />
return; //with the return the local pFoo is destroyed automatically <br />
//reference counter = 0<br />
//internally the std::shared_ptr destroys the reference to the Foo object<br />
} <br />
<br />
}}<br />
<br />
So there's no need for Bar to care about deleting pFoo, which increases memory management severely. <br />
<br />
{{example<br />
|code=<br />
<br />
void SomeOtherAction(std::shared_ptr<Bar> pBar)<br />
{<br />
std::shared_ptr<Foo> pFoo = pBar->getFoo(); //a copy of the shared pointer is created<br />
//reference counter = 2<br />
<br />
pFoo->doSomething(); <br />
<br />
return; //local pFoo is destroyed<br />
//reference counter = 1<br />
} <br />
<br />
}}<br />
<br />
When the function returns, pBar is deleted, but there is still a copy of the std::shared_ptr outside the scope of the function, therefor the internal Bar object will not be destroyed, which sustains the reference to the Foo object, which is in turn not destroyed either. <br />
<br />
The usage of smart_ptr allows us to easily pass and return references to objects without running into memory leaks or invalid attempts to access deleted references. They are thus a cornerstone of modern memory management.<br />
<br />
==weak_ptr==<br />
{{todo}}<br />
<br />
==auto_ptr==<br />
<br />
The {{tt|auto_ptr<>}} was the first implementation of a smart pointer in the standard library. However, when the new C++ standard {{mark c++11}} was defined, it was replaced by the [[#unique_ptr|unique_ptr]] template due to some design flaws and new features of the language.<br />
Since this is a tutorial, the {{tt|auto_ptr<>}} is not explained here. Use the new, improved smart pointers described above.</div>Cubbihttps://en.cppreference.com/book/Main_PageMain Page2020-05-26T22:20:20Z<p>Cubbi: rm fmbox that is now hacked into every title</p>
<hr />
<div>{{fmbox | class=noprint | style=font-size: 0.8em | text='''This wiki is in alpha stage'''. There's absolutely no warranty that the content here is accurate.<br />
}}<br />
{{fmbox | image=none | class=noprint | style=font-size: 0.8em | text=Read [[Help:Wiki syntax|this]] if you are new to the syntax used in MediaWiki wikis<br />
}}<br />
{{title|C++ book}}<br />
{| class="mainpagetable" cellspacing=0 style="width:100%; white-space:nowrap;"<br />
|- class="row rowtop"<br />
| colspan=4 |<br />
<span style="font-size: 2em;">Introduction</span><br/><br />
<span style="font-size: 0.8em;">Look here if you have little experience in C++ programming</span><br />
|- class="row rowbottom"<br />
|<br />
[[intro/intro | Introduction to C++]]<br />
<br />
[[glossary | Glossary]]<br />
<br />
[[intro/hello_world | Hello world]]<br />
<br />
[[intro/comments | Comments]]<br />
<br />
[[intro/variables | Variables]]<br />
<br />
[[intro/operators | Operators]]<br />
<br />
[[intro/constants | Constants and literals]]<br />
<br />
<div class="mainpagediv"><br />
[[intro/escape | Escape characters]]<br />
</div><br />
<br />
[[intro/control | Flow control]]<br />
<br />
<div class="mainpagediv"><br />
[[intro/control/if | <code>if</code> statement]]<br/><br />
[[intro/control/switch | <code>switch</code> statement]]<br/><br />
[[intro/control/while | <code>while</code> loop]]<br/><br />
[[intro/control/do_while | <code>do</code>-<code>while</code> loop]]<br/><br />
[[intro/control/for | <code>for</code> loop]]<br/><br />
[[intro/control/break_continue | <code>break</code>-<code>continue</code>]]<br/><br />
</div><br />
<br />
|<br />
<br />
[[intro/scope | Variable scope]]<br />
<br />
[[intro/types | Variable types]]<br />
<br />
[[intro/strings | Strings]]<br />
<br />
[[intro/vector | Vectors]]<br />
<br />
[[intro/range_for | Range-for]]<br />
<br />
[[intro/functions | '''Functions''']]<br />
<div class="mainpagediv"><br />
[[intro/reference | References]]<br/><br />
[[intro/const | const]]<br/><br />
[[intro/function_overloading | Function overloading]]<br/><br />
[[intro/function_templates | Function templates]]<br />
</div><br />
<br />
[[intro/io | '''Input/output''']]<br />
<div class="mainpagediv"><br />
[[intro/output | Output]]<br/><br />
[[intro/input | Input]]<br/><br />
[[intro/files | Files]]<br />
</div><br />
<br />
|<br />
<br />
[[intro/classes | '''Classes''']]<br />
<div class="mainpagediv"><br />
[[intro/encapsulation | Encapsulation]]<br/><br />
[[intro/class_template | Class templates]]<br/><br />
[[intro/inheritance | Inheritance]]<br/><br />
[[intro/polymorphism | Polymorphism]]<br/><br />
[[intro/operator_overloading | Operator overloading]]<br/><br />
[[intro/abstract_classes | Abstract classes]]<br />
</div><br />
<br />
[[intro/namespaces | '''Namespaces''']]<br />
<br />
|<br />
<br />
[[intro/stdlib | '''Standard library''']]<br />
<div class="mainpagediv"><br />
[[intro/containers | Containers]]<br/><br />
[[intro/containers | Iterators]]<br/><br />
[[intro/containers | Pairs and Ranges]]<br/><br />
[[intro/containers | Algorithms]]<br/><br />
[[intro/math | Numerics]]<br/><br />
....<br />
</div><br />
<br />
[[intro/abstraction | Abstraction]]<br />
<br />
[[intro/smart_pointers | Smart pointers]]<br />
<br />
[[intro/enums | Enumerated types]]<br />
<br />
[[intro/exceptions | Exceptions]]<br />
<br />
<br />
|-<br />
| colspan=4 | <span style="margin:12px;">What's below is a just a copy of the structure of the regular cppreference wiki. Improvements are very welcome.</span><br />
|- class="row rowtop"<br />
| colspan=4 |<br />
<span style="font-size: 2em;">Advanced</span><br/><br />
<span style="font-size: 0.8em;">Look here if you already know C++ a bit</span><br />
|- class="row"<br />
|<br />
<br />
[[undefined_behavior | Undefined behavior]]<br />
<br />
[[uninitialized | Uninitialized variables]]<br />
<br />
'''[[storage_durations | Storage duration]]'''<br />
<div class="mainpagediv"><br />
[[storage_duration_auto | Automatic]]<br/><br />
[[storage_duration_static | Static]]<br/><br />
[[storage_duration_thread_local | Thread-local]]<br />
</div><br />
<br />
'''[[memory_management | Memory management]]'''<br />
<div class="mainpagediv"><br />
[[pointers | Pointers]]<br/><br />
[[arrays | Arrays]]<br/><br />
[[dynamic_allocation | Dynamic allocation]]<br/><br />
[[stack and heap | Stack and heap]]<br />
</div><br />
<br />
[[move_semantics | Move semantics]]<br />
<br />
[[unions | Unions]]<br />
<br />
'''[[basic_concepts | Basic concepts]]'''<br />
<div class="mainpagediv"><br />
[[basics | Basic definitions]]<br><br />
[[keywords | Keywords]]<br><br />
[[escape | Escape sequences]]<br><br />
[[ascii | ASCII chart]]<br><br />
[[types | Fundamental types]]<br><br />
[[scope | Scope]] -<br />
[[lifetime | Lifetime]]<br><br />
[[lookup | Name lookup ]]<br><br />
[[odr | One-definition rule]]<br><br />
[[memory_model | Memory model]]<br><br />
[[translation_phases | Phases of translation]]<br><br />
<!-- TODO: more sufficiently important and generic ideas --><br />
</div><br />
<br />
'''[[preprocessor | Preprocessor]]'''<br />
<div class="mainpagediv"><br />
[[preprocessor_conditional | #if - #ifdef - #ifndef]]<br><br />
[[preprocessor_replace | #define]]<br><br />
[[preprocessor_include | #include]]<br><br />
[[preprocessor_warning | #warning]] -<br />
[[preprocessor_error | #error]]<br><br />
[[preprocessor_impl | #pragma]] -<br />
[[preprocessor_line | #line]]<br><br />
</div><br />
<br />
'''[[expressions | Expressions]]'''<br />
<div class="mainpagediv"><br />
[[expressions#Operators | Operators]]<br><br />
[[expressions#Conversions | Conversions]]<br><br />
[[expressions#Literals | Literals]]<br><br />
[[identifiers | Identifiers]]<br><br />
[[operator_precedence | Operator precedence]]<br><br />
[[value_category | Value categories]]<br><br />
[[eval_order | Evaluation order]]<br><br />
[[sizeof | {{tt|sizeof}}]] -<br />
[[alignof | {{tt|alignof}}]] -<br />
[[typeid | {{tt|typeid}}]]<br><br />
[[new | {{tt|new}}]] -<br />
[[delete | {{tt|delete}}]]<br><br />
[[constant_expression | Constant expressions]]<br><br />
</div><br />
<br />
|<br />
<br />
'''[[statements | Statements]]'''<br />
<div class="mainpagediv"><br />
[[if | {{tt|if}}]] -<br />
[[switch | {{tt|switch}}]]<br><br />
[[for | {{tt|for}}]] -<br />
[[range for | range-{{tt|for}}]]<br/><br />
[[while | {{tt|while}}]] -<br />
[[do | {{tt|do}}-{{tt|while}}]]<br><br />
[[continue | {{tt|continue}}]] -<br />
[[break | {{tt|break}}]]<br/><br />
[[goto | {{tt|goto}}]] -<br />
[[return | {{tt|return}}]]<br><br />
</div><br />
<br />
'''[[declarations | Declaration]]'''<br />
<div class="mainpagediv"><br />
[[namespace | Namespace declaration]]<br><br />
[[namespace_alias | Namespace alias]]<br><br />
[[reference | Lvalue and rvalue references]]<br><br />
[[pointer | Pointers]] -<br />
[[array | Arrays]]<br><br />
[[enum | Enumerations and enumerators]]<br><br />
[[storage_duration | Storage duration and linkage]]<br><br />
[[cv | Cv-specifiers]] -<br />
[[constexpr | {{tt|constexpr}}]]<br><br />
[[decltype | {{tt|decltype}}]] -<br />
[[auto | {{tt|auto}}]] <br><br />
[[alignas | {{tt|alignas}}]] <br><br />
[[typedef | {{tt|typedef}}]] -<br />
[[type_alias | Type alias]]<br><br />
[[attributes | Attributes]] <br><br />
</div><br />
<br />
'''[[initialization | Initialization]]'''<br />
<div class="mainpagediv"><br />
[[default_initialization | Default initialization]]<br><br />
[[value_initialization | Value initialization]]<br><br />
[[copy_initialization | Copy initialization]]<br><br />
[[direct_initialization | Direct initialization]]<br><br />
[[aggregate_initialization | Aggregate initialization]]<br><br />
[[list_initialization | List initialization]]<br><br />
[[reference_initialization | Reference initialization]]<br><br />
</div><br />
<br />
|<br />
<br />
'''[[functions | Functions]]'''<br />
<div class="mainpagediv"><br />
[[function | Function declaration]]<br><br />
[[default_arguments | Default arguments]]<br><br />
[[variadic_arguments | Variadic arguments]]<br><br />
[[lambda | Lambda expression]]<br><br />
[[inline | {{tt|inline}} specifier]]<br><br />
[[adl | Argument-dependent lookup]]<br><br />
[[overload_resolution | Overload resolution]]<br><br />
[[operators | Operator overloading]]<br><br />
</div><br />
<br />
'''[[classes | Classes]]'''<br />
<div class="mainpagediv"><br />
[[class | Class types]] -<br />
[[union | Union types]]<br><br />
[[data_members | Data members]]<br/><br />
[[member_functions | Member functions]]<br><br />
[[static | Static members]]<br/><br />
[[nested_types | Nested types]]<br><br />
[[member_template | Member templates]]<br><br />
[[derived_class | Derived class]]<br/><br />
[[using_declaration | {{tt|using}}-declaration]]<br><br />
[[virtual | Virtual function]]<br/><br />
[[abstract_class | Abstract class]]<br><br />
[[bit_field | Bit fields]]<br><br />
[[this | {{tt|this}}]]<br><br />
[[access | Access specifiers]] <br><br />
[[friend | {{tt|friend}} specifier]]<br><br />
[[default_constructor | Default constructor]]<br/><br />
[[copy_constructor | Copy constructor]]<br><br />
[[as_operator | Copy assignment]]<br/><br />
[[destructor | Destructor]]<br><br />
[[move_constructor | Move constructor]]<br/><br />
[[move_operator | Move assignment]]<br><br />
[[initializer_list | Member initializer lists]]<br><br />
</div><br />
<br />
|<br />
<br />
'''[[exceptions | Exceptions]]'''<br />
<div class="mainpagediv"><br />
[[throw | {{tt|throw}}]]<br><br />
[[try_catch | {{tt|try}}-{{tt|catch}}]]<br><br />
[[noexcept_spec | {{tt|noexcept}} specifier]]<br><br />
[[noexcept | {{tt|noexcept}} operator]]<br><br />
[[except_spec | Exception specification]]<br><br />
</div><br />
<br />
'''[[templates | Templates]]'''<br />
<div class="mainpagediv"><br />
[[class_template | Class template]]<br><br />
[[function_template | Function template]]<br><br />
[[variable_template | Variable template]]{{mark c++14}}<br><br />
[[template_specialization | Explicit specialization]]<br><br />
[[partial_specialization | Partial specialization]]<br><br />
[[dependent_name | Dependent names]]<br><br />
[[parameter_pack | Parameter packs]]<br/><br />
[[sizeof... | {{tt|sizeof...}}]]<br><br />
</div><br />
<br />
'''[[misc | Miscellaneous]]'''<br />
<div class="mainpagediv"><br />
[[history | History of C++]]<br><br />
[[main_function | Program startup]]<br><br />
[[termination | Program termination]]<br><br />
[[asm | Inline assembly]]<br><br />
[[raii | RAII]] -<br />
[[rule_of_three | Rule of three]]<br><br />
[[as_if | As-if rule]]<br/><br />
[[copy_elision | Copy elision]]<br/><br />
[[ebo | Empty base optimization]]<br><br />
</div><br />
<br />
|}</div>Cubbihttps://en.cppreference.com/book/Template:titleTemplate:title2020-05-26T22:19:52Z<p>Cubbi: hack to place the main page's warning fmbox into every single page (since all pages begin with a title template) - I don't know enough mediawiki magic to do something like a bot-edit</p>
<hr />
<div><onlyinclude>{{DISPLAYTITLE:{{{1|}}}}}<br />
{{fmbox | class=noprint | style=font-size: 1.6em | text='''Warning: This wiki is part of the deprecated and unmaintained CppReference Book project. For up-to-date information on C++, see the main reference at [http://en.cppreference.com cppreference.com]. '''<br />
}}<br />
<!--<br />
--></onlyinclude><br />
{{documentation}}</div>Cubbihttps://en.cppreference.com/book/Template:mark_until_c99Template:mark until c992013-04-09T13:12:41Z<p>Cubbi: +</p>
<hr />
<div>{{mark|until C99}}<noinclude><br />
{{documentation | Template:mark/doc}}<br />
</noinclude></div>Cubbihttps://en.cppreference.com/book/Template:mark_structTemplate:mark struct2012-04-25T02:28:24Z<p>Cubbi: C has structs</p>
<hr />
<div>{{mark|struct}}<noinclude><br />
{{documentation | Template:mark/doc}}<br />
</noinclude></div>Cubbi