【问题标题】:Treat vector<int*> as vector<const int*> without copying (C++0x)将 vector<int*> 视为 vector<const int*> 而不复制 (C++0x)
【发布时间】:2012-05-03 04:30:52
【问题描述】:

一个类包含一个std::vector&lt;int*&gt;。外部代码需要对该向量进行只读访问,不应修改内容(指针或其内容)。在类中,值可能会发生变化(例如double_values(),因此无法将它们存储为std::vector&lt;const int*&gt;。

有没有办法在不复制的情况下将std::vector&lt;int*&gt; 作为std::vector&lt;const int*&gt; 返回?感觉应该有,因为 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;
}

【问题讨论】:

  • vector and const的可能重复
  • @Bo:这个问题并没有回答这个问题,真的。由于指针间接,WeaselFox' 也无关紧要。
  • @Xeo - 另一个问题的答案告诉我们为什么它不起作用。还有什么其他答案?
  • 可以接受高级概念解决方法。在不更改代码内容的情况下如何允许访问?有没有办法制作副本(感觉没有必要,这可能是限制性能的因素)。我可以简单地做一个void* 演员,但我担心这是糟糕的设计。

标签: c++ constants accessor


【解决方案1】:

您可以通过自定义迭代器提供 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&lt;typename std::vector&lt;int*&gt;::const_iterator, const int&gt; 用于const_val_iter_type,我们可以通过.base() 修改指向的值(但不能直接像x[0] = -1 那样),所以这个解决方案并不通用。

【讨论】:

    【解决方案2】:

    如果您仍然想保留 const 指针,则返回向量将意味着一个副本。

    但是,如果您的目标是提供一种在不修改值或修改其容器的情况下使用值的方法,那么基于访问者模式的算法可能是一个非常好的解决方案,特别是现在我们可以使用 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;
    }
    

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

    【讨论】:

    • 显然。你为什么要问,究竟是什么?这里在类外部使用 std::for_each 将无济于事,因为它需要公开真正的容器迭代器或制作副本,这是要避免的问题。我只能用 std::for_each 替换 for_each_value 中的循环,但没有任何好处。我的回答的重点是容器没有副本,无论遍历算法是什么,如果您知道类的用户需要哪种遍历,则不需要公开类的内容。显然,如果您不知道,请接受 YAGNI。
    • 话虽如此,某些情况下需要类通过迭代器公开内容。但我认为这对于特定问题没有必要。
    • 那么,如果没有暴露迭代器,你的 for-range 循环将如何工作?如果是,您的for_each_value 与std::for_each 有何不同? YAGNI 一切都很好,但对我来说,你把它颠倒了。为什么在不需要时编写自己的 for_each 函数,因为标准库已经为您完成了?
    • 看起来我不明白你的问题,因为我想我已经在上面回答了。或者,也许我们正在谈论同一个循环?如果这是类型的目的,我说暴露迭代器是好的,我补充说我认为这里不合适。该类型不是容器,它可以容纳一个。它不应该不受控制地公开其数据。
    猜你喜欢
    • 2016-11-11
    • 2020-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-07
    • 1970-01-01
    • 2023-01-20
    • 2013-03-15
    相关资源
    最近更新 更多