简体   繁体   English

如何从函数返回 grpc::ClientContext ?

[英]How can I return a grpc::ClientContext from a function?

I am trying to avoid repetitive code by having a function for creating ClientContexts.我试图通过具有用于创建 ClientContext 的函数来避免重复代码。 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).如果没有将返回类型设为右值引用,或者没有显式 std::move(我使用的是 C++ 11,所以我相信 RVO 和复制省略号不能保证),它不会编译。

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).它尝试创建一个临时对象并将其复制到stream_context ,这是无法完成的,因为ClientContext的复制构造函数是私有的(未删除)。

Is there any way to do this without using unique_ptr ?有没有办法在不使用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错误:'grpc::ClientContext::ClientContext(const grpc::ClientContext&)' 在此上下文中是私有的

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:在完成以下操作之前,可以使用std::unique_ptr解决该问题:

https://github.com/grpc/grpc/issues/16680 https://github.com/grpc/grpc/issues/16680

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

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