1 // Copyright 2020 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include <cppgc/allocation.h>
6 #include <cppgc/default-platform.h>
7 #include <cppgc/garbage-collected.h>
8 #include <cppgc/heap.h>
9 #include <cppgc/member.h>
10 #include <cppgc/visitor.h>
11 
12 #include <iostream>
13 #include <memory>
14 #include <string>
15 
16 /**
17  * This sample program shows how to set up a stand-alone cppgc heap.
18  */
19 
20 /**
21  * Simple string rope to illustrate allocation and garbage collection below.
22  * The rope keeps the next parts alive via regular managed reference.
23  */
24 class Rope final : public cppgc::GarbageCollected<Rope> {
25  public:
Rope(std::string part,Rope * next=nullptr)26   explicit Rope(std::string part, Rope* next = nullptr)
27       : part_(part), next_(next) {}
28 
Trace(cppgc::Visitor * visitor) const29   void Trace(cppgc::Visitor* visitor) const { visitor->Trace(next_); }
30 
31  private:
32   std::string part_;
33   cppgc::Member<Rope> next_;
34 
operator <<(std::ostream & os,const Rope & rope)35   friend std::ostream& operator<<(std::ostream& os, const Rope& rope) {
36     os << rope.part_;
37     if (rope.next_) {
38       os << *rope.next_;
39     }
40     return os;
41   }
42 };
43 
main(int argc,char * argv[])44 int main(int argc, char* argv[]) {
45   // Create a default platform that is used by cppgc::Heap for execution and
46   // backend allocation.
47   auto cppgc_platform = std::make_shared<cppgc::DefaultPlatform>();
48   // Initialize the process. This must happen before any cppgc::Heap::Create()
49   // calls.
50   cppgc::DefaultPlatform::InitializeProcess(cppgc_platform.get());
51   // Create a managed heap.
52   std::unique_ptr<cppgc::Heap> heap = cppgc::Heap::Create(cppgc_platform);
53   // Allocate a string rope on the managed heap.
54   auto* greeting = cppgc::MakeGarbageCollected<Rope>(
55       heap->GetAllocationHandle(), "Hello ",
56       cppgc::MakeGarbageCollected<Rope>(heap->GetAllocationHandle(), "World!"));
57   // Manually trigger garbage collection. The object greeting is held alive
58   // through conservative stack scanning.
59   heap->ForceGarbageCollectionSlow("CppGC example", "Testing");
60   std::cout << *greeting << std::endl;
61   // Gracefully shutdown the process.
62   cppgc::ShutdownProcess();
63   return 0;
64 }
65