0

カスタム型の動的配列で特に注意することはありますか?

ConditionParameter の動的配列を作成しようとしています (以下の定義)。

ConditionParameter* m_params;
...
m_params = new ConditionParameter[m_numParams];

しかし、上記の行の結果は、タイプ ConditionParameter の 1 つの新しいオブジェクトのみであり、そのアドレスは m_params に格納されます。

struct ConditionParameter
{
    ConditionParameter() :
    type(OBJ_TYPE_OBJECT),
    semantic(OP_SEMANTIC_TYPE_NONE),
    instance(NULL),
    attrib(ATTRIB_TYPE_NONE),
    value(0)
    {}

    ConditionParameter(const ConditionParameter& other)
    {
        attrib = other.attrib;
        instance = other.instance;
        semantic = other.semantic;
        type = other.type;
        value = other.value;
    }

    ConditionParameter& operator = (ConditionParameter& other)
    {
        attrib = other.attrib;
        instance = other.instance;
        semantic = other.semantic;
        type = other.type;
        value = other.value;
        return *this;
    }

    ObjectType          type;   

    OperandSemanticType semantic;
    Object*             instance;
    AttributeType       attrib;
    int                 value;
};
4

2 に答える 2

6

しかし、上記の行の結果は、タイプ ConditionParameter の 1 つの新しいオブジェクトであり、そのアドレスは m_params に格納されます。

いいえ、結果はm_numParams--によって返される最初ConditionParameterのポインタへのポインタです。new

new[]オブジェクトの連続配列を作成しConditionParameterます。最初のものは にありm_paramsます。[]次のように、演算子を使用して後続のインスタンス化にアクセスできます。

ConditionParameter* secondParam = &m_params[1];

ちょっとした " sprintf debugging " でこれを証明できます:

ConditionParameter() :
    type(OBJ_TYPE_OBJECT),
    semantic(OP_SEMANTIC_TYPE_NONE),
    instance(NULL),
    attrib(ATTRIB_TYPE_NONE),
    value(0)
    {
      cout << "Constructor\n";
    }
于 2013-10-30T18:19:45.763 に答える
1

もちろんnew、割り当てられたメモリ ブロックの最初の要素へのポインタを返します。ConditionParameter*そのため、 new の結果を、実際には へのポインターである型の変数に代入しますConditionParameter。ただし、これは単一のオブジェクトが割り当てられたことを意味するものではありません。new が null を返さない限り、指定した数のオブジェクトが割り当てられます。

于 2013-10-30T18:17:42.050 に答える