内存
智能指针
shared_ptr< vector< string>> sp1;
if ( sp1) {
cout << "has object" << endl;
}
sp1. get ( ) ;
shared_ptr< vector< string>> sp2 ( sp1) ;
shared_ptr< vector< string>> sp3;
sp1. swap ( sp3) ;
sp2 = sp3;
sp1. use_count ( ) ;
sp1. unique ( ) ;
auto sp4 = make_shared< vector< string>> ( vector< string> { "a" , "b" } ) ;
for ( auto s : * sp4) {
cout << s << endl;
}
{
auto sp5 = make_shared< vector< string>> ( vector< string> { "a" , "b" } ) ;
}
auto sp6 = make_shared< string> ( string ( "aaa" ) ) ;
auto sp7 = make_shared< string> ( ) ;
sp6. reset ( new string ( "aa" ) ) ;
unique_ptr< vector< string>> up1;
auto p1 = up1. release ( ) ;
unique_ptr< vector< string>> up2 ( p1) ;
std:: shared_ptr< DFFile> file;
std:: shared_ptr< Directories> dir = std:: static_pointer_cast< Directories> ( file) ;
自定义释放操作
void customizeOpt ( string * sp) {
delete sp;
}
void customizeOptTest ( ) {
shared_ptr< string> sp1 ( new string ( "aaa" ) , customizeOpt) ;
unique_ptr< string, decltype ( customizeOpt) * > up1 ( new string ( "aaa" ) , customizeOpt) ;
}
自己管理内存
int * np1 = new int ;
delete np1;
int * np2 = new int ( 0 ) ;
delete np2;
auto * np3 = new auto ( string ( "aaa" ) ) ;
delete np3;
auto * np4 = new string ( "aaa" ) ;
if ( np4 == nullptr ) {
}
delete np4;
const string * np5 = new const string ( "a" ) ;
delete np5;
np5 = nullptr ;
int * arrp1 = new int [ 10 ] ;
delete [ ] arrp1;
弱智能指针
auto sp1 = make_shared< string> ( string ( "aaaaaa" ) ) ;
weak_ptr< string> wp1 ( sp1) ;
wp1. use_count ( ) ;
wp1. expired ( ) ;
sp1. reset ( new string ( "aaaaaa" ) ) ;
auto p = wp1. lock ( ) ;
if ( ! p) {
cout << wp1. expired ( ) << endl;
cout << wp1. use_count ( ) << endl;
}
wp1. reset ( ) ;
allocator内存分配与构造分离
allocator< string> alloc1;
auto start = alloc1. allocate ( 10 ) ;
auto end = start;
alloc1. construct ( end, "a" ) ;
end++ ;
alloc1. construct ( end, "ab" ) ;
end++ ;
auto start1 = alloc1. allocate ( 20 ) ;
uninitialized_copy ( start, end, start1) ;
uninitialized_copy_n ( start, 2 , start1) ;
uninitialized_fill ( start1, start1 + 20 , "a" ) ;
while ( end != start)
{
end-- ;
alloc1. destroy ( end) ;
}
alloc1. deallocate ( start, 10 ) ;
使用头文件
#include <memory>