(GeekBand)C++オブジェクト向けポインタクラス

2747 ワード

1.ポインタ付クラス設定
ポインタ付きクラスには、コピー構造、コピー付与、および構造関数が含まれている必要があります.
1.Stringクラス解析
stringクラスにはプライベートなポインタがメモリ内の文字列を指しており、この文字列を使用する必要がある場合はポインタでメモリを申請します.
class string
{
public:
        //    ,       ,     0
        string( const char* cstr = 0 );
        //      
        string( const String& str );
        //     " = ",      
        string& operator = ( const string& str );
        ~string();

        //
        char* get_c_str() const { return m_data; }

private:
        char* m_data;
};

inline
string::string( const char* cstr )
{
    if( cstr )
    {
        m_data = new char[ strlen(cstr)+1 ];
        strcpy( m_data, cstr );
    }
    //     ,      
    else
    {
        m_data = new char[1];
        *m_data = '\0';
    }
}

inline
string& string::operator = ( const string& str )
{
    //  this      str     ,      。
    if( this == &str ) return *this;
    else
    {
        delete[] m_data;
        m_data = new char[ strlen(str.m_data)+1 ];
        strcpy( m_data, str.m_data );
        return *this;
    }
}

//      
inline
string::string( const string& str )
{
    //  str.m_data        ,        friend
    m_data = new char[ strlen( str.m_data )+1 ];
    strcpy( m_data, str.m_data );
}

//                  ,        ,                 
inline
string::~string()
{
    delete[] m_data;
}


2.スタック、スタックについて
1.スタック(stack)
stackはscopeのメモリ領域に存在します.関数を呼び出すと、関数自体がstackを形成し、受信したパラメータ、戻りアドレス、local objectsを配置します.関数本体(function body)内で宣言された任意の変数は、使用されるメモリブロックが上記stackから取得される.
2.ヒープ(heap)
システムheapとは、オペレーティングシステムによって提供されるglobalメモリ空間を指し、プログラムは、そこからいくつかのブロックを動的に割り当てることができる.
例:
class complex
{ ... };
......
//  C          ,       ,    static       。
complex C( 1, 2 );

{
    //c1       ,              ,     local object auto object。
    complex c1( 1, 2 ); 

    //c2     scope        ,        。
    static complex c2( 1, 2 );

    //  new     ,    memory   ctor,       p    。
    complex* p = new complex( 1, 2 ); 
    //              ,           。
    delete p;
}

分析:
1.newで単一オブジェクトを作成するには:
complex* pc = new complex( 1, 2 );

上記のコードは、コンパイラで次のように動作します.
complex *pc;

void* mem = operator new( sizeof( complex ) );//    malloc    。
pc = static_cast( mem );//  
pc->complex::complex( 1, 2 );

2.deleteを使用してメモリを解放するには:
String* pc = new String( "Hello!" );
...
delete pc;

このコードはコンパイラでdtorを呼び出してからメモリを解放します.
complex::~complex( pc );//    ,     String  。
operator delete( pc );//       ,    free( pc )。

array newを使用して配列を作成する場合は、delete[]を使用してメモリの解放を行う必要があります.