Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I return a grpc::ClientContext from a function?

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

like image 576
tonicsoft Avatar asked Jun 15 '26 01:06

tonicsoft


1 Answers

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));
like image 80
Max Vollmer Avatar answered Jun 17 '26 14:06

Max Vollmer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!