相关疑难解决方法(0)

C++使用放置新的未定义行为构造对象两次?

我遇到了一些让我感到恐惧的代码.基本上它遵循这种模式:

class Foo
{
  public:
    //default constructor
    Foo(): x(0), ptr(nullptr)  
    {
      //do nothing
    }

    //more interesting constructor
    Foo( FooInitialiser& init): x(0), ptr(nullptr) 
    {
      x = init.getX();
      ptr = new int;
    }
    ~Foo()
    {
      delete ptr;
    }

  private:
    int x;
    int* ptr;
};


void someFunction( FooInitialiser initialiser )
{
   int numFoos = MAGIC_NUMBER;
   Foo* fooArray = new Foo[numFoos];   //allocate an array of default constructed Foo's

   for(int i = 0; i < numFoos; ++i)
   {
       new( fooArray+ i) Foo( initialiser );    //use …
Run Code Online (Sandbox Code Playgroud)

c++ placement-new new-operator language-lawyer

6
推荐指数
1
解决办法
761
查看次数