Only IMP::Pointer objects should be used to store pointers to instances of these objects.
The source code is as follows:
/** * \file example/ExampleRefCounted.h * \brief An example showing how to make a simple ref counted object * * Copyright 2007-2010 IMP Inventors. All rights reserved. */ #ifndef IMPEXAMPLE_EXAMPLE_REF_COUNTED_H #define IMPEXAMPLE_EXAMPLE_REF_COUNTED_H #include "example_config.h" #include <IMP/RefCounted.h> IMPEXAMPLE_BEGIN_NAMESPACE //! An example simple object which is reference counted. /** Only IMP::Pointer objects should be used to store pointers to instances of these objects. The source code is as follows: \include ExampleRefCounted.h \include ExampleRefCounted.cpp */ class IMPEXAMPLEEXPORT ExampleRefCounted: public RefCounted { std::vector<double> data_; public: ExampleRefCounted(const std::vector<double> &data); double get_data(unsigned int i) const { IMP_USAGE_CHECK(i < data_.size(), "Index " << i << " out of range."); return data_[i]; } /* Make sure that it can't be allocated on the stack The macro defines an empty destructor. In general, you want destructors to be empty since they are hard to maintain. */ IMP_REF_COUNTED_DESTRUCTOR(ExampleRefCounted); }; IMPEXAMPLE_END_NAMESPACE #endif /* IMPEXAMPLE_EXAMPLE_REF_COUNTED_H */
/** * \file ExampleRefCounted.cpp * \brief An example reference counted object. * * Copyright 2007-2010 IMP Inventors. All rights reserved. * */ #include "IMP/example/ExampleRefCounted.h" #include "IMP/Pointer.h" IMPEXAMPLE_BEGIN_NAMESPACE ExampleRefCounted::ExampleRefCounted(const std::vector<double> &data ): data_(data){ } void usage_example() { std::vector<double> data(1000, -1); // this would not compile // ExampleRefCounted rcstack; // create a new object and store it in a ref counted pointer IMP_NEW(ExampleRefCounted, rc, (data)); // reference count is 1 // another object with another copy of the data Pointer<ExampleRefCounted> rc_other= new ExampleRefCounted(data); // have two pointers point to the object Pointer<ExampleRefCounted> rc2=rc; // reference count is 2 // the object is still around since rc2 points to it rc=NULL; // reference count is 1 std::cout << rc2->get_data(100); // the object will be deleted on exit } IMPEXAMPLE_END_NAMESPACE
Public Member Functions | |
ExampleRefCounted (const std::vector< double > &data) | |
double | get_data (unsigned int i) const |
Friends | |
template<class T > | |
void | IMP::internal::unref (T *) |