Reputation: 57
I have a function foo(T value)
, where T
is move-only. I want to (for some reasons) allocate value
of type T
and call foo
.
Can I do it like this?
{
std::unique_ptr<T> ptr = make_unique<T>(T());
foo(std::move(*ptr));
}
If it's not clear: I want to get rid of new
and delete
in this code:
void ServeForever(uint16_t port) {
Acceptor acceptor;
acceptor.BindTo(port).ExpectOk();
acceptor.Listen().ExpectOk();
while (true) {
Socket* socket = new Socket(acceptor.Accept());
Spawn([socket]() {
HandleClient(std::move(*socket));
delete socket;
}).Detach();
}
}
Upvotes: 1
Views: 113
Reputation: 19223
There is no reason to involve pointers at all:
void HandleCLient(Socket socket){
//...
}
//...
while (true) {
//Construct in-place
Spawn([s=Socket(acceptor.Accept)]() mutable
{
HandleClient(std::move(s));
}).Detach();
}
Thanks @rafix07 for pointing out the need for adding mutable
.
Upvotes: 3