Logo ROOT   6.14/05
Reference Guide
vo001_AdoptOrOwnMemory.C
Go to the documentation of this file.
1 /// \file
2 /// \ingroup tutorial_vecops
3 /// \notebook -nodraw
4 /// In this tutorial we learn how the RVec class can be used to
5 /// adopt existing memory or allocate some.
6 ///
7 /// \macro_code
8 ///
9 /// \date May 2018
10 /// \author Danilo Piparo
11 
12 // We use this class for didactic purposes: upon copy, a line is printed to the terminal.
13 class UponCopyPrinter {
14 public:
15  UponCopyPrinter() = default;
16  UponCopyPrinter(UponCopyPrinter &&) = default;
17  UponCopyPrinter(const UponCopyPrinter &) { std::cout << "Invoking copy c'tor!" << std::endl; }
18 };
19 
20 using namespace ROOT::VecOps;
21 
23 {
24 
25  // One of the essential features of RVec is its ability of adopting and owning memory.
26  // Internally this is handled by the ROOT::Detail::VecOps::RAdoptAllocator class.
27 
28  // Let's create an RVec of UponCopyPrinter instances. We expect no printout:
30 
31  // Let's adopt the memory from v into v2. We expect no printout:
32  RVec<UponCopyPrinter> v2(v.data(), v.size());
33 
34  // OK, let's check the addresses of the memory associated to the two RVecs It is the same!
35  std::cout << v.data() << " and " << v2.data() << std::endl;
36 
37  // Now, upon reallocation, the RVec stops adopting the memory and starts owning it. And yes,
38  // a copy is triggered. Indeed internally the storage of the RVec is an std::vector. Moreover,
39  // the interface of the TVec is very, very similar to the one of std::vector: you have already
40  // noticed it when the `data()` method was invoked, right?
41 
42  v2.push_back(UponCopyPrinter());
43 
44  // Of course, now the addresses are different.
45  std::cout << v.data() << " and " << v2.data() << std::endl;
46 }
A "std::vector"-like collection of values implementing handy operation to analyse them...
Definition: RVec.hxx:146
SVector< double, 2 > v
Definition: Dict.h:5