C++ 修改、更改和“删除”原始指针时是否需要指针副本?

C++ 修改、更改和“删除”原始指针时是否需要指针副本?,c++,pointers,C++,Pointers,表示“在第10行中创建副本的原因是,循环通过递增运算符(++)修改正在使用的指针。new返回的原始指针需要完整存储,第26行中相应的delete[]需要使用new返回的地址而不是任何随机值来调用” 在下列情况下 { type* ptr = new type[size]; // line A /* some code, for example ptr++; // legal but dangerous/bad

表示“在第10行中创建副本的原因是,循环通过递增运算符(
++
)修改正在使用的指针。new返回的原始指针需要完整存储,第26行中相应的
delete[]
需要使用new返回的地址而不是任何随机值来调用”


在下列情况下

{
  type* ptr = new type[size];      // line A
  /*
     some code, for example
     ptr++;                        // legal but dangerous/bad
  */
  delete[] ptr;                    // line B
}
变量
ptr
的值,即指向的地址,在
A
B
行中必须相同。否则,这是未定义的行为,并导致崩溃(如果你幸运的话)。在第二个代码清单中,您没有使用指针变量在元素上循环,而是使用索引。所以,原始指针从未改变,您满足了条件

有几种方法可以确保满足此要求

  • 您可以将指针声明为
    const

    {
      type * const ptr = new type[size];  // not: type const*ptr
      // ptr++;                           // illegal: would give a compiler error
      delete[] ptr;
    }
    
  • 你可以使用


  • 最后一个选项是最方便的,因为它还允许您更改分配的内存量,或在最初分配的内存之外添加元素(当向量自动重新分配和展开时)。

    代码墙,请发布“是”。出于报价中给出的原因。您的版本不修改
    pNumbers
    ,因此不需要副本。声明为
    int*const pNumbers
    以捕获意外修改,否则您是安全的。
    {
      type* ptr = new type[size];      // line A
      /*
         some code, for example
         ptr++;                        // legal but dangerous/bad
      */
      delete[] ptr;                    // line B
    }
    
    {
      type * const ptr = new type[size];  // not: type const*ptr
      // ptr++;                           // illegal: would give a compiler error
      delete[] ptr;
    }
    
    {
      std::unique_ptr<type[]> ptr = new type[size];
      /* some code */
    }   // memory is automatically freed at end of scope of ptr
    
    {
      std::vector<type> vec(size);
      /* some code */
    }   // memory is automatically freed at end of scope of ptr