将 vector<int*> 视为 vector<const int*>而不复制 (C++0x)



类包含一个std::vector<int*> .外部代码需要对此向量进行只读访问,不应能够修改内容(指针或其内容)。在类内部,值可能会更改(例如 double_values(),因此将它们存储为std::vector<const int*>是不可能的。

有没有办法在不复制的情况下将std::vector<int*>作为std::vector<const int*>返回?感觉应该有,因为 const 只是在编译时操作,说什么可以修改,什么不能修改。

代码:(使用 g++ -std=c++0x 编译)

class ReadOnlyAccess
{
public:
  ReadOnlyAccess(const std::vector<int*> & int_ptrs_param):
    int_ptrs(int_ptrs_param)
  {
  }
  const std::vector<int*> & get_int_ptrs() const
  {
    return int_ptrs;
  }
  std::vector<const int*> safely_get_int_ptrs() const
  {
    // will not compile (too bad):
    //    return int_ptrs;
    // need to copy entire vector
    std::vector<const int*> result(int_ptrs.size());
    for (int k=0; k<int_ptrs.size(); k++)
      result[k] = int_ptrs[k];
    return result;
  }
  void double_values()
  {
    for (int*p : int_ptrs)
      *p *= 2;
  }
  void print() const
  {
    for (const int * p : int_ptrs)
      std::cout << *p << " ";
    std::cout << std::endl;
  }
private:
  std::vector<int*> int_ptrs;
};
int main() {
  ReadOnlyAccess roa(std::vector<int*>{new int(10), new int(20), new int(100)});
  std::vector<const int*> safe_int_ptrs = roa.safely_get_int_ptrs();
  // does not compile (good)
  // *safe_int_ptrs[0] = -100000;
  roa.print();
  const std::vector<int*> & int_ptrs = roa.get_int_ptrs();
  // changes are made to the internal class values via the accessor! nooooo!
  *int_ptrs[0] = -100000;
  roa.print();
  return 0;
}

返回向量将意味着一个副本,如果你无论如何都想保留常量指针。

但是,如果您的目标是提供一种在不修改它们或修改其容器的情况下使用这些值的方法,那么基于访问者模式的算法可能是一个很好的解决方案,特别是现在我们可以使用 lambda 表达式:

#include <vector>
#include <iostream>
class Data
{
public:
    //...whatever needed to fill the values
    // here we assume that Func is equivalent to std::function< void ( int )> or std::function< void (const int& ) > and can return anything that will be ignored here.
    template< class Func > 
    void for_each_value( Func func ) const // read-only
    {
        for( const int* value : m_values ) // implicit conversion
        {
             func( *value ); // read-only reference (const &), or copy
             // if func needs to work with the adress of the object, it still can by getting a reference to it and using & to get it's adress
        }
    }

    void print() const
    {
        std::cout << "nData values: n";
        for_each_value( []( const int value ) { std::cout << "    "<< value << 'n'; } );
    }
    void count_values() const { return m_values.size(); }
private:
    std::vector<int*> m_values;
};

int main()
{
    Data data;
    // ... whatever needed to fill the data
    data.print();    
    std::vector<int> modified_values;
    data.for_each_value( [&]( int value ) { modified_values.push_back( value + 42 ); } );
    return 0;
}

如果你理解这一点,并且使用这些值的不同方式可以简化为一些半通用的算法,那么它将使您的代码更简单,并允许您将数据保存在结构中,而不是暴露它的胆量。

您可以通过自定义迭代器提供 const 值的视图。一个简单的方法是使用boost::iterator

#include <boost/iterator/indirect_iterator.hpp>
class ReadOnlyAccess
{
// ...
    typedef boost::indirect_iterator<const int* const*, const int> const_val_iter_type;
    const_val_iter_type cval_begin() {
        return it_t{const_cast<const int* const*>(&int_ptrs[0])};
    }
}
int main() {
    // ...
    auto x = roa.cval_begin();
    std::cout << x[0] <<' ' << x[1] << x[2] <<'n';
    // we can still access the pointers themselves via .base() member function:
    for (int i=0; i<3; ++i)
        assert(x.base()[i] == safe_int_ptrs[i]);
    // the values are read-only, the following does not compile:
    // x[0] = -1;
    // **x.base() = -1;
    // *x.base() = nullptr;
}

如果我们使用 boost::indirect_iterator<typename std::vector<int*>::const_iterator, const int> 表示const_val_iter_type,我们可以通过 .base() 修改指向的值(但不能像例如 x[0] = -1 ),因此此解决方案不是通用的。

最新更新