Scoped_ptr smart pointer (2)

Source: Internet
Author: User

Common Operations of Boost: scoped_ptr:

It can be simplified as follows:

Namespace boost {

Template <typename T>
Class scoped_ptr: noncopyable {
Public:
Explicit scoped_ptr (T * p = 0 );
~ Scoped_ptr ();

Void reset (T * p = 0 );

T & operator * () const;

T * operator-> ()
Const;
T * Get () const;

Void swap (scoped_ptr & B );
};

Template <typename T>

Void swap (scoped_ptr <t> & A, scoped_ptr <t> & B );

}

 

Its common operations are as follows:

Member Functions

Function

Operator *()

Access the members of the managed object in Reference Form

Operator-> ()

Access the members of the managed object as pointers

Get ()

Release managed objects and manage another object

Swap (scoped_ptr & B)

Exchange two boost: Objects managed by scoped_ptr

 

The following test code demonstrates the basic usage of these functions.

# Include
<String>
# Include <iostream>

# Include <boost/scoped_ptr.hpp>
# Include <boost/scoped_array.hpp>

# Include <boost/config. HPP>
# Include <boost/detail/lightweight_test.hpp>

Void test ()
{
// Test scoped_ptr with a built-in type
Long * Lp = new
Long;
Boost: scoped_ptr <long> Sp (LP );
Boost_test (sp. Get () = LP );
Boost_test (Lp = sp. Get ());
Boost_test (& * sp = LP );

* Sp = 1234568901l;
Boost_test (* sp = 1234568901l );
Boost_test (* Lp = 1234568901l );

Long * lp2 = new
Long;
Boost: scoped_ptr <long> SP2 (lp2 );

Sp. Swap (SP2 );
Boost_test (sp. Get () = lp2 );
Boost_test (sp2.get () = LP );

Sp. Reset (null );
Boost_test (sp. Get () = NULL );

}

Void main ()
{
Test ();
}

 

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.