简体   繁体   English

如何在unique_ptr上调用函数调用运算符?

[英]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 : 还有另一个具有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. 如果将client构造为remote对象的一部分,则此方法有效。 However if you pass ownership to remote via a unique_ptr how do you call the function call operator? 但是,如果您通过unique_ptr将所有权传递给remote ,您如何调用函数调用运算符?

Upon changing the call to client()->push(d.begin(), d.end()); 在更改对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 . 产生的错误消息表明问题出在此原因是因为推送是在unique_ptr而不是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' 现在,使用.get()在基础对象上工作,但没有函数调用运算符: client.get()->push(m.begin(), m.end()); // error: 'class client_connection<unsigned char>' has no member named 'push' 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 ? 如何在unique_ptr包含的对象上调用函数调用运算符?

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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM