' P '

whatever I will forget

C++ <cstring>を使うメンバ変数が存在する場合のコンストラクタ定義

なんかこれはメモっておいたほうがよいと思ったのでメモ!

Testクラスに、char *strというメンバ変数が存在する場合です。

#include <cstring>
#include <XXX.h> //XXX.hがローカルにあることを前提

//no args constructor
Test::Test()
    //nullptrで初期化
    : str{nullptr} {
    //heapに1byte charを確保 
    str = new char[1];
    //null terminateしておく
    *str = ¥0;
}

//overloaded constructor (with 1 argument)
Test::Test(const char *s)
    :str(nullptr) {
    if (str == nullptr) {
        str = new char[1];
        *str = ¥0;
    } else {
        //null terminateされてるはずなので、実際に渡される値の長さに+1した長さのcharをheapに確保
        str = new char[std::strlen(s) + 1];
        std::strcpy(str,s);
    }

//copy constructor
Test::Test(const Test &source)
    :str(nullptr) {
        //null terminateされてるはずなので、実際に渡される値の長さに+1した長さのcharをheapに確保
        str = new char[std::strlen(source.str) + 1];
        std::strcpy(str,source.str);
    }
}

まあ、null terminateだるいわ、って話