Gobelijn API documentation  - generated for commit a0cbea7
 All Classes Namespaces Files Functions Variables Typedefs Friends Macros Pages
raii/memory/main.cpp
Go to the documentation of this file.
1 /*
2  * This file is part of the gobelijn software.
3  * Gobelijn is free software: you can redistribute it and/or modify it
4  * under the terms of the GNU General Public License as published by the
5  * Free Software Foundation, either version 3 of the License, or any later
6  * version. Gobelijn is distributed in the hope that it will be useful, but
7  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
8  * or FITNESS FOR A PARTICULAR PURPOSE.
9  * See the GNU General Public License for details. You should have received
10  * a copy of the GNU General Public License along with the software. If not,
11  * see <http://www.gnu.org/licenses/>.
12  *
13  * Copyright 2016, Jan Broeckhove.
14  */
20 #include "buffer.h"
21 #include <iostream>
22 
23 using namespace Raii;
24 
28 void printBuffer(const Buffer& buf)
29 {
30  std::cout << "size: " << buf.GetSize() << ", data: ";
31  for (unsigned int i = 0; i < buf.GetSize(); i++) {
32  if (i > 0)
33  std::cout << ", ";
34 
35  // Convert the buffer's items to integers before printing them.
36  // Otherwise, they will be printed as their ASCII values (which are
37  // probably gibberish)
38  std::cout << static_cast<int>(buf[i]);
39  }
40  std::cout << std::endl;
41 }
42 
43 int main()
44 {
45  // 'buf1' is allocated and initialized
46  Buffer buf1(4);
47  buf1[1] = 2;
48  printBuffer(buf1);
49  {
50  // Copy-construct 'buf2' from 'buf1'; a new memory block is created for
51  // 'buf2', which has the same contents as 'buf1's memory block.
52  Buffer buf2 = buf1;
53  buf2[3] = 16;
54  printBuffer(buf1);
55  printBuffer(buf2);
56  // Move-assign 'buf2' to 'buf1'. 'buf1's memory block is now
57  // deallocated, and replaced by 'buf2's memory block.
58  buf1 = std::move(buf2);
59  // 'buf2's memory block is not deallocated here, because it has been
60  // moved to 'buf1'.
61  }
62  printBuffer(buf1);
63  // 'buf2's memory block is deallocated.
64 }
int main()
size_t GetSize() const
Gets the buffer's size, in bytes.
Definition: buffer.h:55
void printBuffer(const Buffer &buf)
Prints the contents of a buffer.
A buffer of bytes, with a fixed size.
Definition: buffer.h:30
RAII Buffer class.