use*_*ser 6 c++ const accessor
一个类包含一个std::vector<int*>.外部代码需要只读访问此向量,不应该能够修改内容(既不是指针也不是内容).在类中,值可能会改变(例如double_values(),因此将它们存储为a 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;
}
Run Code Online (Sandbox Code Playgroud)
如果您无论如何都想保留 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;
}
Run Code Online (Sandbox Code Playgroud)
如果您理解这一点,并且使用这些值的不同方法可以简化为一些半通用算法,那么它将使您的代码更简单,并允许您将数据保留在结构中,而不是暴露它的内部。
| 归档时间: |
|
| 查看次数: |
767 次 |
| 最近记录: |