1 //===- llvm/unittest/ADT/polymorphic_ptr.h - polymorphic_ptr<T> tests -----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "gtest/gtest.h"
11 #include "llvm/ADT/polymorphic_ptr.h"
12 #include "llvm/Support/raw_ostream.h"
20 S *clone() { return new S(*this); }
24 // A function that forces the return of a copy.
26 T dummy_copy(const T &arg) { return arg; }
28 TEST(polymorphic_ptr_test, Basic) {
29 polymorphic_ptr<S> null;
30 EXPECT_FALSE((bool)null);
32 EXPECT_EQ((S*)0, null.get());
35 polymorphic_ptr<S> p(s);
38 EXPECT_TRUE(p != null);
39 EXPECT_FALSE(p == null);
45 EXPECT_EQ(s, p.operator->());
46 EXPECT_EQ(s, p.get());
49 EXPECT_EQ(s, p.take());
50 EXPECT_FALSE((bool)p);
56 EXPECT_EQ(s, p.operator->());
57 EXPECT_EQ(s, p.get());
60 polymorphic_ptr<S> p2((llvm_move(p)));
61 #if !LLVM_HAS_RVALUE_REFERENCES
62 // 'p' may not have been moved from in C++98, fake it for the test.
65 EXPECT_FALSE((bool)p);
67 EXPECT_TRUE((bool)p2);
76 EXPECT_FALSE((bool)p2);
79 // Force copies and that everything survives.
80 polymorphic_ptr<S> p3 = dummy_copy(polymorphic_ptr<S>(p));
81 EXPECT_TRUE((bool)p3);
86 // Force copies of null without trying to dereference anything.
87 polymorphic_ptr<S> null_copy = dummy_copy(polymorphic_ptr<S>(null));
88 EXPECT_FALSE((bool)null_copy);
89 EXPECT_TRUE(!null_copy);
90 EXPECT_EQ(null, null_copy);
95 virtual Base *clone() = 0;
96 virtual StringRef name() { return "Base"; }
99 struct DerivedA : Base {
100 virtual DerivedA *clone() { return new DerivedA(); }
101 virtual StringRef name() { return "DerivedA"; }
103 struct DerivedB : Base {
104 virtual DerivedB *clone() { return new DerivedB(); }
105 virtual StringRef name() { return "DerivedB"; }
108 TEST(polymorphic_ptr_test, Polymorphism) {
109 polymorphic_ptr<Base> a(new DerivedA());
110 polymorphic_ptr<Base> b(new DerivedB());
112 EXPECT_EQ("DerivedA", a->name());
113 EXPECT_EQ("DerivedB", b->name());
115 polymorphic_ptr<Base> copy = dummy_copy(a);
117 EXPECT_EQ("DerivedA", copy->name());
119 copy = dummy_copy(b);
121 EXPECT_EQ("DerivedB", copy->name());
123 // Test creating a copy out of a temporary directly.
124 copy = dummy_copy<polymorphic_ptr<Base> >(new DerivedA());
126 EXPECT_EQ("DerivedA", copy->name());