Alex Alex - 2 months ago 18
C++ Question

Hiding raw pointers by providing a "proxy" pointer

Is there a way to hide a raw pointer behind a "proxy" or "fake" pointer that will provide access to the functionality of the raw pointer without revealing it's address?

The managing class for the raw pointer might look as follows:

template<typename T>
class hidden_ptr
{
public:
hidden_ptr(T *RawPointer);
~hidden_ptr();

T *get()
{
return new proxy_pointer<T>(raw_pointer)
}
};


Then to use it:

class Foo
{
public:
Foo();
~Foo();

void do_bar();
void do_bar2();
};

int main()
{
Foo *raw_pointer = new Foo();
hidden_ptr<Foo> hidden(raw_pointer);

Foo *proxy = hidden.get();

proxy->do_bar();
proxy->do_bar2();

delete proxy; //The raw pointer is still safe till the hidden object destructs
}


If there is a way, what would the proxy_ptr look like?

AnT AnT
Answer

The only way to satisfy the combination of requirements that you provided so far is to make class Foo a dual-mode class of sorts: it should be able to act as the primary (hidden) object, as well as a public proxy to itself, i.e. to another Foo object.

I.e. an "ugly" implementation of that would looks as follows

class Foo
{
    Foo *redirect_to = nullptr;
    Foo(Foo *redirect_to) : redirect_to(redirect_to) { ... }

public:
    Foo() { ... }
    ~Foo() { ... }

    Foo *get_proxy() { return new(this); }

    void do_bar() {
      if (redirect_to) {
        return redirect_to->do_bar();
      ...
    }

    void do_bar2() {
      if (redirect_to) {
        return redirect_to->do_bar2();
      ...
    }

    ...
};

After that you will be able to create and delete proxies accessible through a Foo * pointer. Whether to wrap such proxies into smart pointers of any kind is up to you - this is beside the point.

int main()
{
    Foo *raw_pointer = new Foo();

    Foo *proxy = raw_pointer->get_proxy();

    proxy->do_bar();
    proxy->do_bar2();

    delete proxy;
}

Again, you can add your hidden_ptr into the mix, if you wish.

A closer look at the above immediately suggests it can be implemented much more elegantly through a pImpl-style implementation, in which all objects become proxies pointing to a hidden implementation class. But it appears that you don't like that approach for some reason (which I was not able to figure out so far).