Boost: scoped_ptr is very similar to STD: auto_ptr. It is a simple smart pointer that can ensure that the object is automatically released after it leaves the scope.
The previous code and its output:
1 #include <string> 2 #include <iostream> 3 #include <boost/scoped_ptr.hpp> 4 5 class implementation 6 { 7 public: 8 ~implementation() { std::cout <<"destroying implementation\n"; } 9 void do_something() { std::cout << "did something\n"; }10 };11 12 void test()13 {14 boost::scoped_ptr<implementation> impl(new implementation());15 impl->do_something();16 }17 18 void main()19 {20 std::cout<<"Test Begin ... \n";21 test();22 std::cout<<"Test End.\n";23 }
The output result is:
Test begin...
Did something
Destroying implementation
Test end.
We can see that when the implementation class is out of its impl scope, it will be automatically deleted, so as to avoid Memory leakage caused by forgetting to manually call Delete.
Boost: scoped_ptr features:
The implementation of Boost: scoped_ptr is very similar to STD: auto_ptr. It uses the objects on a stack to manage objects on a stack, so that the objects on the stack are automatically deleted as the objects on the stack are destroyed. The difference is that boost: scoped_ptr has more strict limits-it cannot be copied. This means that the boost: scoped_ptr pointer cannot be converted to its ownership.
- Cannot change ownership
Boost: The object lifecycle managed by scoped_ptr is limited to only one interval (between "{}" where the pointer is located) and cannot be passed out of the range, which means boost :: scoped_ptr objects cannot be returned as function values (STD: auto_ptr can ).
- Cannot share ownership
This is similar to STD: auto_ptr. This feature makes the pointer easy to use. On the other hand, it also causes weak functionality-it cannot be used in STL containers.
- Cannot be used to manage array objects
Because boost: scoped_ptr deletes the managed object through delete, and the array object must be deleted through deletep [], boost: scoped_ptr cannot manage the array object, to manage array objects, use the boost: scoped_array class.
Select boost: scoped_ptr and STD: auto_ptr:
The functions and operations of Boost: scoped_ptr and STD: auto_ptr are similar, how to select between them depends on whether the ownership of the managed object needs to be transferred (for example, whether it needs to be returned as a function ). If this is not required, you can use boost: scoped_ptr to enable the compiler to perform more rigorous checks to find some incorrect assignment operations.