Question

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);

i.e. remove the unneeded temporary variable. Is this possible in 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? I cannot change the API. Shouldn't this be a use case for rvalue references?

Was it helpful?

Solution

First of all, that's not what "temporary" means in 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?

Yes.

I cannot change the 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. 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top