scoped_nsobject.h (2007B)
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */ 3 // Copyright (c) 2009 The Chromium Authors. All rights reserved. 4 // Use of this source code is governed by a BSD-style license that can be 5 // found in the LICENSE file. 6 7 #ifndef BASE_SCOPED_NSOBJECT_H_ 8 #define BASE_SCOPED_NSOBJECT_H_ 9 10 #import <Foundation/Foundation.h> 11 #include "base/basictypes.h" 12 13 // scoped_nsobject<> is patterned after scoped_ptr<>, but maintains ownership 14 // of an NSObject subclass object. Style deviations here are solely for 15 // compatibility with scoped_ptr<>'s interface, with which everyone is already 16 // familiar. 17 // 18 // When scoped_nsobject<> takes ownership of an object (in the constructor or 19 // in reset()), it takes over the caller's existing ownership claim. The 20 // caller must own the object it gives to scoped_nsobject<>, and relinquishes 21 // an ownership claim to that object. scoped_nsobject<> does not call 22 // -retain. 23 template <typename NST> 24 class scoped_nsobject { 25 public: 26 typedef NST* element_type; 27 28 explicit scoped_nsobject(NST* object = nil) : object_(object) {} 29 30 ~scoped_nsobject() { [object_ release]; } 31 32 void reset(NST* object = nil) { 33 [object_ release]; 34 object_ = object; 35 } 36 37 bool operator==(NST* that) const { return object_ == that; } 38 39 bool operator!=(NST* that) const { return object_ != that; } 40 41 operator NST*() const { return object_; } 42 43 NST* get() const { return object_; } 44 45 void swap(scoped_nsobject& that) { 46 NST* temp = that.object_; 47 that.object_ = object_; 48 object_ = temp; 49 } 50 51 // scoped_nsobject<>::release() is like scoped_ptr<>::release. It is NOT 52 // a wrapper for [object_ release]. To force a scoped_nsobject<> object to 53 // call [object_ release], use scoped_nsobject<>::reset(). 54 NST* release() { 55 NST* temp = object_; 56 object_ = nil; 57 return temp; 58 } 59 60 private: 61 NST* object_; 62 63 DISALLOW_COPY_AND_ASSIGN(scoped_nsobject); 64 }; 65 66 #endif // BASE_SCOPED_NSOBJECT_H_