graham.reeds graham.reeds - 11 months ago 91
C++ Question

How do you call the function call operator on a unique_ptr?

If a class has a function call operator that returns a reference to a container (heavily redacted):

class client_connection {
public:
concurrent_queue<T>& operator()() { return client; }
concurrent_queue<T> client;
};


And another class which has a member of
client_connection
:

class remote {
public:
void get_version() {
auto d = ... something to generate data ...
client().push(d.begin(), d.end());
}
...
client_connection client;
};


This works if
client
is constructed as part of the
remote
object. However if you pass ownership to
remote
via a
unique_ptr
how do you call the function call operator?

Upon changing the call to
client()->push(d.begin(), d.end());
the resulting error message suggests that the issue is because the push is on the
unique_ptr
, not the
client_connection
.

Using
.get()
is now working on the underlying object but without function call operator:
client.get()->push(m.begin(), m.end()); // error: ‘class client_connection<unsigned char>’ has no member named ‘push’


However trying various combinations to invoke the function call operator all fail. How do you call the function call operator on an object contained in a
unique_ptr
?

Answer Source

You do it like this

client->operator()().push(m.begin(), m.end());

You need to actually call the operator because you have a pointer. Alternatively, dereference the unique pointer instead:

(*client)().push(m.begin(), m.end());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download