Reputation: 25938
How can I ensure a variable (pointer) cannot be passed/accessed outside of a class?
I know the obvious answer is to make the variable private or protected but the code is part of an API and the class will be subclassed by users who can simply create a public get
function to overcome that design.
class Component
{
public:
GUID gUid;
template<typename T>
T* addComponent()
{
T* cmp = new T();
auto res = components.emplace(cmp->gUid, cmp);
return cmp;
}
protected:
std::unordered_map<GUID, Component*> components;
};
class UpdaterComponent : public Component
{
public:
void init()
{
nCmp = addComponent<NetworkComponent>(); // ok to store and access component within class
}
// Not ok to expose sub components to outside
NetworkComponent* getNetworkComponent()
{
return nCmp;
}
private:
NetworkComponent* nCmp;
};
Upvotes: 0
Views: 53
Reputation: 275770
Access control protects against mistakes not malice.
They can simply copy/paste your header, insert a friend
function into your class definition, include their copy of the header, then bypass your private
or protected
rules as they wish.
You can hide the layout of the struct behind a pImpl
type pattern, but even then they can reverse engineer the layout and get access to it.
What you want to do cannot be done, barring support from the hardware/OS with encrypted memory.
Upvotes: 0
Reputation: 5658
You mention, that the class it will be subclassed by users, and you are worried about get()
functions, that will let them access the pointer.
In that case: make it private. That's what it for. This will forbid inherited classes to access the pointer, too.
Upvotes: 2