1 //===- llvm/ADT/scoped_ptr.h - basic smart pointer --------------*- C++ -*-===//
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 // This file defines the scoped_ptr smart pointer: scoped_ptr mimics a built-in
11 // pointer except that it guarantees deletion of the object pointed to, either
12 // on destruction of the scoped_ptr or via an explicit reset(). scoped_ptr is a
13 // simple solution for simple needs.
15 //===----------------------------------------------------------------------===//
17 // (C) Copyright Greg Colvin and Beman Dawes 1998, 1999.
18 // Copyright (c) 2001, 2002 Peter Dimov
20 // Distributed under the Boost Software License, Version 1.0. (See
21 // accompanying file llvm/docs/BOOST_LICENSE_1_0.txt or copy at
22 // http://www.boost.org/LICENSE_1_0.txt )
24 // http://www.boost.org/libs/smart_ptr/scoped_ptr.htm
27 #ifndef LLVM_SCOPED_PTR_HPP_INCLUDED
28 #define LLVM_SCOPED_PTR_HPP_INCLUDED
34 // verify that types are complete for increased safety
35 template<class T> inline void checked_delete(T * x) {
36 // intentionally complex - simplification causes regressions
37 typedef char type_must_be_complete[ sizeof(T)? 1: -1 ];
38 (void) sizeof(type_must_be_complete);
42 // scoped_ptr mimics a built-in pointer except that it guarantees deletion
43 // of the object pointed to, either on destruction of the scoped_ptr or via
44 // an explicit reset(). scoped_ptr is a simple solution for simple needs;
45 // use shared_ptr or std::auto_ptr if your needs are more complex.
47 template<class T> class scoped_ptr // noncopyable
53 scoped_ptr(scoped_ptr const &);
54 scoped_ptr & operator=(scoped_ptr const &);
56 typedef scoped_ptr<T> this_type;
60 typedef T element_type;
62 explicit scoped_ptr(T * p = 0): ptr(p) // never throws
66 ~scoped_ptr() // never throws
68 llvm::checked_delete(ptr);
71 void reset(T * p = 0) // never throws
73 assert( (p == 0 || p != ptr) && "scoped_ptr: self-reset error"); // catch self-reset errors
74 this_type(p).swap(*this);
77 T & operator*() const // never throws
79 assert(ptr != 0 && "scoped_ptr: Trying to dereference a null pointeur");
83 T * operator->() const // never throws
85 assert(ptr != 0 && "scoped_ptr: Trying to dereference a null pointeur");
89 T * get() const // never throws
94 // implicit conversion to "bool"
95 typedef T * this_type::*unspecified_bool_type;
97 operator unspecified_bool_type() const // never throws
99 return ptr == 0? 0: &this_type::ptr;
102 bool operator! () const // never throws
107 void swap(scoped_ptr & b) // never throws
115 template<class T> inline void swap(scoped_ptr<T> & a, scoped_ptr<T> & b) // never throws
120 // get_pointer(p) is a generic way to say p.get()
122 template<class T> inline T * get_pointer(scoped_ptr<T> const & p)
129 #endif // #ifndef LLVM_SCOPED_PTR_HPP_INCLUDED