C++11のdefaultとdeleteキーワード

3102 ワード

C 11の新しい特性はあまりにも多く、この2つのキーワードに注目する人は少なくなっています.その理由の一つは、コンパイラのサポートが遅すぎることです(VS VS 2013までサポートされています)が、この2つのキーワードは本当に役に立ちます.次に見てみましょう.
【defaultキーワード】
まず文字列クラスがあります.
class CString
{
    char* _str;

public:
    // 
    CString(const char* pstr) : _str(nullptr)
    {
        UpdateString(pstr);
    }

    // 
    ~CString()
    {
        if (_str)
            free(_str);
    }

public:
    void UpdateString(const char* pstr) throw()
    {
        if (pstr == nullptr)
            return;

        if (_str)
            free(_str);

        _str = (char*)malloc(strlen(pstr) + 1);
        strcpy(_str,pstr);
    }

public:
    char* GetStr() const throw()
    {
        return _str;
    }
};
このように使用できます.
auto str = std::make_unique("123");
printf(str->GetStr());
しかし、これはだめです.
auto str = std::make_unique(); // , 

はい、defaultを使います.
class CString
{
    char* _str = nullptr;
    
public:
    CString() = default;

public:
    // 
    CString(const char* pstr) : _str(nullptr)
    {
        UpdateString(pstr);
    }

    // 
    ~CString()
    {
        if (_str)
            free(_str);
    }

public:
    void UpdateString(const char* pstr) throw()
    {
        if (pstr == nullptr)
            return;

        if (_str)
            free(_str);

        _str = (char*)malloc(strlen(pstr) + 1);
        strcpy(_str,pstr);
    }

public:
    char* GetStr() const throw()
    {
        return _str;
    }
};

次のように使用できます.
auto str_def = std::make_unique();
str_def->UpdateString(“123”);
printf(str_def->GetStr() == nullptr ? "None":str_def->GetStr());

【deleteキーワード】
メモリを自動的に申請し、RAI管理を行うクラスがあるとします.
(コピー構造コピー付与移動構造なんて書かないでください)
template
class CStackMemoryAlloctor
{
    mutable T* _ptr;

public:
    explicit CStackMemoryAlloctor(size_t size) throw() : _ptr(nullptr)
    {
        _ptr = (T*)malloc(size);
    }

    ~CStackMemoryAlloctor()
    {
        if (_ptr)
            free(_ptr);
    }

public:
    operator T*() const throw()
    {
        T* tmp = _ptr;
        _ptr = nullptr;
        return tmp;
    }

public:
    T* GetPtr() const throw()
    {
        return _ptr;
    }
};

このクラスを使用します.
CStackMemoryAlloctor str(128);
wchar_t* pstr = str.GetPtr();
wcscpy(pstr,L"123
"); wprintf(pstr);

しかし、他の人もこのように使用することができます.
auto p = std::make_unique>(128);

このクラスは依然としてnewを黙認することができるので、私たちは人にnewをさせたくありません.
private:
    void* operator new(std::size_t)
    {
        return nullptr;
    }
newをprivateに設定すればいいのですが、他の人がnewを試してみると、見たエラーメッセージは見るに堪えません.の
C 11のdeleteは人間的になりました
public:
    void* operator new(std::size_t) = delete;

newを試してみると、ヒントは非常に友好的で、この方法は削除されました.
このdeleteは、コピー構造や鶏の毛をコピーする価値を与えるなど、不快なものを削除するために使用することができます.