A class contains a std::vector<int*>
. External code needs read-only access to this vector, should not be able to modify the contents (neither the pointers or their contents). Inside the class, the values may change (e.g. double_values()
, and so storing them as a std::vector<const int*>
is not possible.
Is there a way to return the std::vector<int*>
as a std::vector<const int*>
without making a copy? It feels like there should be, because const is simply operating at compile time to say what can and cannot be modified.
Code: (compile with 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;
}