Reputation: 4489
If I have a:
class myClass
{
...
list<myObject*> objectList;
};
How can I write a getObjectListPointer()
function that return a pointer to this objectList
in a way, that itself and its content cannot be modified?
Which means, if I have
list<myObject*>* pointer = getObjectListPointer();
then pointer
itself and pointer->at(i) for any i
cannot be modified?
Like where should I put const
?
Ok, my purpose is to able to modify objectList
with in myClass
but not other places, but I need to access the value of objectList
and its content's value in other class, how should design the code?
Upvotes: 1
Views: 86
Reputation: 2162
#include <list>
#include <iostream>
class myClass {
std::list<float*> container;
public:
myClass(){
float* f = new float;
*f = 0.5f;
container.push_back(f);
}
const std::list<const float*>* containerConst(){
return (std::list<const float*>*)&container;
}
};
int main(){
myClass instance;
std::cout << *instance.containerConst()->front() << std::endl;
return 0;
}
Outputs 0.5
.
Pointers can be freely cast to const and the compiler usually does so implicitly, but the template system can't handle that by itself. Casting isn't the nicest solution since it results in a new template instantiation, but if the resulting class has the same data layout it works.
Upvotes: 1
Reputation: 217593
With
struct myClass
{
std::list<const myObject*> getObjectListPointer() const
{
// Create a copy with const pointers
return {std::begin(objectList), std::end(objectList)};
}
std::list<myObject*> objectList;
};
You may then do
myClass instance;
const auto& pointer = instance.getObjectListPointer();
// cannot modify list `objectList`, and all `myObject` would be `const`
Upvotes: 2