VtkFloatArray from STL vector

Suppose you are using code that computes data in a std::vector<float> and you want to expose that data as a vtkFloatArray. This can come up in database readers that provide STL-based containers for reading data. Normally, you'd copy the data from the vector into a new vtkFloatArray, wasting memory and time. If the std::vector is going to be deleted anyway, you can steal its memory buffer and wrap it as a vtkFloatArray.

class vtkFloatArrayFromFloatVector : public vtkCommand
{
public:
    static vtkFloatArrayFromFloatVector *New()
    {
        return new vtkFloatArrayFromFloatVector;
    }

    // Install the observer on the DeleteEvent.
    vtkFloatArray *MakeArray(int nComponents, vector<float> &obj)
    {
        // Steal the data from the input vector by swapping with a new vector
        // that we control.
        this->vec = new vector<float>();
        this->vec->swap(obj);

        // Wrap the stolen data as a vtkPoints. Indicate that the vtkFloatArray
        // object is not allowed to delete the vector storage.
        vtkFloatArray *arr = vtkFloatArray::New();
        arr->SetNumberOfComponents(nComponents);
        arr->SetArray(&this->vec->operator[](0), this->vec->size(), 1);

        // Ensure that this object will be called in response to the
        // vtkPoints object getting deleted.
        this->Id = arr->AddObserver(vtkCommand::DeleteEvent, this);

        return arr;
    }

    // This method gets invoked when the vtkPoints object gets deleted.
    virtual void Execute(vtkObject *object, unsigned long, void *)
    {
        // Delete the vector data.
        delete this->vec;
        this->vec = NULL;

        // Remove this object as an observer on the vtkPoints.
        object->RemoveObserver(this->Id);

        // Delete this observer object.
        this->UnRegister();
    }

protected:
    vtkFloatArrayFromFloatVector() : vec(NULL), Id(0) {}
    virtual ~vtkFloatArrayFromFloatVector() {}

private:
    vector<float> *vec;
    unsigned long  Id;

    void operator=(const vtkFloatArrayFromFloatVector &); // not implemented
    vtkFloatArrayFromFloatVector(const vtkFloatArrayFromFloatVector &); // not implemented
};

Usage

vtkDataArray *
avtXXXFileFormat::GetVar(/*args*/)
{
   std::vector<float> lotsofdata;
   read_the_data(lotsofdata);

   return vtkFloatArrayFromFloatVector::New()->MakeArray(1, lotsofdata);
}