使用new []在C++中创建自定义类型的动态数组

alb*_*gil -1 c++ arrays types dynamic

有没有特别需要注意的动态自定义类型数组?

我正在尝试创建ConditionParameter的动态数组(下面的定义)

ConditionParameter* m_params;
...
m_params = new ConditionParameter[m_numParams];
Run Code Online (Sandbox Code Playgroud)

但是上面一行的结果只是ConditionParameter类型的一个新对象,其地址存储在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;
};
Run Code Online (Sandbox Code Playgroud)

Joh*_*ing 6

但是上面一行的结果只是ConditionParameter类型的一个新对象,其地址存储在m_params中.

不,结果是m_numParams实例化ConditionParameter- 指向第一个返回的指针new.

new[]创建一个有条件的ConditionParameter对象数组.第一个位于m_params.您可以使用[]运算符进行后续实例化,如下所示:

ConditionParameter* secondParam = &m_params[1];
Run Code Online (Sandbox Code Playgroud)

您可以通过一些" sprintf调试 " 向自己证明这一点:

ConditionParameter() :
    type(OBJ_TYPE_OBJECT),
    semantic(OP_SEMANTIC_TYPE_NONE),
    instance(NULL),
    attrib(ATTRIB_TYPE_NONE),
    value(0)
    {
      cout << "Constructor\n";
    }
Run Code Online (Sandbox Code Playgroud)