1

当我想共享数据时,我经常会在 C++ 中使用 operator[] (const size_t& i) 搞得一团糟。我想问是否有我应该使用的设计模式 - 或者完全是更好的方法。

编写一个复杂的矢量容器说明了我的问题——尽管我在编写其他容器时也遇到了类似的问题。

这是我要编写的代码:

class complex; //forward declaration to my complex number container.

//my complex vector container 
class cvec{
    private:
      size_t m_size;  //The number of complex numbers in the vector
      /* I want my data stored 
       * real(0), imag(0), real(1), imag(1) ... real(m_size-1), imag(m_size-1) 
       * so that I can easily pass the data to blas routines - for example.
       */
      double* m_data;  // 2 * m_size
    public:
      //return a reference to constant complex number
      const complex& operator[](const size_t& i) const;  
      //return a reference to a complex number that points to m_data.
      //The user should be able to alter m_data by altering the returned complex number
      complex& operator[](const size_t& i);             
}

它完全反映了我的class vec(这只是一个双打数组)。

我的问题是当以这种方式共享数据时,如何以理智的方式管理对复数的引用。

我现在这样做的方式感觉很丑。我这样定义我的复杂类:

class complex{
  private:
    double* m_data; //a pointer that always contains 2 elements
    bool    m_own;  //whether this class owns the data - or whether the data belongs to cvec
    void alloc_data(); //allocate the memory if m_own == true
  public:
    //A constructor when the complex number owns its data.
    complex(const double& x, const double& y) : m_own(true)
    { alloc_data(); m_data[0] = x; m_data[1]=y;}

    //A constructor when it does not
    complex(double* data) : m_own(false)
    { m_data = data;}

}

然后在 cvec 类中像这样在 std::vector 容器中添加一组引用

 class cvec{ 
 private:    
   ...  
   std::vector<boost::shared_ptr<complex> > m_complex_data;   
   void alloc_data() {  //I use calloc as I believe this is byte aligned while the new operator is not...
     if (m_size>0)
       m_data =  ( double* )  calloc(2*m_size, sizeof(double));

     m_complex_data.resize(m_size);
     for(size_t i=0;i<m_size;++i){
       //Pass a pointer to data to the new complex class
       boost::shared_ptr<complex> cptr(  new complex(m_data + 2*i) );
       m_complex_data[i] =  cptr ;
     }   
   } 
 public:   
   //Return the reference   
   const complex&
   operator[](const size_t& i) const
   {return *m_complex_data[i];}   
 }

这可行,但感觉相当不稳定。当您想在类之间共享数据时,我想问是否有更好的方法来管理引用。以这种方式共享数据时,是否有我应该使用的设计模式。

非常感谢,汤姆

4

0 回答 0