I am trying to avoid repetitive code by having a function for creating ClientContexts. The following code compiles:
template<typename T>
grpc::ClientContext&& context_with_deadline(T duration) {
grpc::ClientContext context;
auto deadline = std::chrono::system_clock::now() + duration;
context.set_deadline(deadline);
return std::move(context);
}
It does not compile without making the return type an rvalue reference, or without the explicit std::move (I am using C++ 11 so I believe RVO and copy ellision is not guaranteed).
In some other scope, I'm now trying to do this, which does not compile:
grpc::ClientContext stream_context = context_with_deadline(std::chrono::milliseconds(3000));
It tries create a temporary object and copy it into stream_context
, which cannot be done because the copy constructor of ClientContext
is private (not deleted).
Is there any way to do this without using unique_ptr
? If not, could this be considered a bug? (it seems the copy constructor should be deleted, not private).
Note: when I say "does not compile", it means the following was emitted by the compiler:
error: 'grpc::ClientContext::ClientContext(const grpc::ClientContext&)' is private within this context
The copy constructor is private, and no user defined move constructor exists, so what you are trying to do is not possible. Instead of returning a new instance from the method, make it take a reference to an instance:
template<typename T>
void context_with_deadline(grpc::ClientContext& context, T duration) {
auto deadline = std::chrono::system_clock::now() + duration;
context.set_deadline(deadline);
}
and then call it like so:
grpc::ClientContext stream_context;
context_with_deadline(stream_context, std::chrono::milliseconds(3000));
It's not possible. The issue can be worked around with std::unique_ptr
until the following is done:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.