aboutsummaryrefslogtreecommitdiffstats
path: root/unittests/ADT/polymorphic_ptr_test.cpp
blob: 90c3385c4f270d52e2d2dd06e8231bf980e7420b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
//===- llvm/unittest/ADT/polymorphic_ptr.h - polymorphic_ptr<T> tests -----===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "gtest/gtest.h"
#include "llvm/ADT/polymorphic_ptr.h"
#include "llvm/Support/raw_ostream.h"

using namespace llvm;

namespace {

struct S {
  S(int x) : x(x) {}
  S *clone() { return new S(*this); }
  int x;
};

// A function that forces the return of a copy.
polymorphic_ptr<S> dummy_copy(const polymorphic_ptr<S> &arg) { return arg; }

TEST(polymorphic_ptr_test, Basic) {
  polymorphic_ptr<S> null;
  EXPECT_FALSE((bool)null);
  EXPECT_TRUE(!null);
  EXPECT_EQ((S*)0, null.get());

  S *s = new S(42);
  polymorphic_ptr<S> p(s);
  EXPECT_TRUE((bool)p);
  EXPECT_FALSE(!p);
  EXPECT_TRUE(p != null);
  EXPECT_FALSE(p == null);
  EXPECT_TRUE(p == s);
  EXPECT_TRUE(s == p);
  EXPECT_FALSE(p != s);
  EXPECT_FALSE(s != p);
  EXPECT_EQ(s, &*p);
  EXPECT_EQ(s, p.operator->());
  EXPECT_EQ(s, p.get());
  EXPECT_EQ(42, p->x);

  EXPECT_EQ(s, p.take());
  EXPECT_FALSE((bool)p);
  EXPECT_TRUE(!p);
  p = s;
  EXPECT_TRUE((bool)p);
  EXPECT_FALSE(!p);
  EXPECT_EQ(s, &*p);
  EXPECT_EQ(s, p.operator->());
  EXPECT_EQ(s, p.get());
  EXPECT_EQ(42, p->x);

  polymorphic_ptr<S> p2((llvm_move(p)));
  EXPECT_FALSE((bool)p);
  EXPECT_TRUE(!p);
  EXPECT_TRUE((bool)p2);
  EXPECT_FALSE(!p2);
  EXPECT_EQ(s, &*p2);

  using std::swap;
  swap(p, p2);
  EXPECT_TRUE((bool)p);
  EXPECT_FALSE(!p);
  EXPECT_EQ(s, &*p);
  EXPECT_FALSE((bool)p2);
  EXPECT_TRUE(!p2);

  // Force copies and that everything survives.
  polymorphic_ptr<S> p3 = dummy_copy(polymorphic_ptr<S>(p));
  EXPECT_TRUE((bool)p3);
  EXPECT_FALSE(!p3);
  EXPECT_NE(s, &*p3);
  EXPECT_EQ(42, p3->x);
}

}