简体   繁体   English

将临时转换为C ++中的引用

[英]Convert temporary to reference in C++

I have the following code: 我有以下代码:

#include <iostream>
#include <llvm/Module.h>
#include <llvm/LLVMContext.h>
#include <llvm/Support/raw_os_ostream.h>

int main()
{
    llvm::Module *TheModule = new llvm::Module("my cool jit", llvm::getGlobalContext());
    llvm::raw_os_ostream os(std::cerr);
    TheModule->print(os, NULL);

    return 0;
}

What I want to do is change this: 我想做的就是更改此:

llvm::raw_os_ostream os(std::cerr);
TheModule->print(os, NULL);

to this: 对此:

TheModule->print(llvm::raw_os_ostream(std::cerr), NULL);

ie remove the unneeded temporary variable. 即删除不需要的临时变量。 Is this possible in C++? 这在C ++中可能吗?

The print function takes a reference: 打印功能参考:

void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const

So is there a way to convert the temporary object to a reference? 那么有没有办法将临时对象转换为引用? Can this be done with C++11 rvalue references? 可以使用C ++ 11右值引用完成此操作吗? I cannot change the API. 我无法更改API。 Shouldn't this be a use case for rvalue references? 这不应该是右值引用的用例吗?

First of all, that's not what "temporary" means in C++. 首先,这不是C ++中“临时”的含义。 You simply have a normal object that is only used once. 您仅具有仅使用一次的普通对象。 Temporaries have no names; 临时工没有名字。 in fact, it's only in your second example that the stream object is a temporary ! 实际上,仅在您的第二个示例中,流对象是临时对象!

Can this be done with C++11 rvalue references? 可以使用C ++ 11右值引用完成此操作吗?

Yes. 是。

I cannot change the API. 我无法更改API。 Shouldn't this be a use case for rvalue references? 这不应该是右值引用的用例吗?

Potentially. 潜在地。 But the API you're using doesn't support them, and you said you can't change it, so that's that. 但是您使用的API不支持它们,并且您说不能更改它,仅此而已。 It is possible to hack around this limitation, but only with a complexity I'm not going to go into here. 可能的黑客绕过这个限制,但只能用复杂,我不打算在这里赘述了。

Honestly, though, I wouldn't worry about it . 不过,老实说, 我不会为此担心 Your compiler is smart enough not to make your first approach any more or less efficient than your second, and the verbosity of your first piece of code actually makes it clearer and easier to read. 您的编译器足够聪明,不会使您的第一种方法比第二种方法效率更高或更低,并且第一段代码的冗长实际上使它更清晰易读。

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

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