Reading this answer regarding returning rvalue references from function got me thinking, how can I write an id
function in C++0x.
Basically, I want id
to be a do nothing function, a function that has no observable effects on the program.
My first attempt is the following:
#include <iostream>
class X
{
public:
X(std::string&& s) : s(std::move(s)) {};
X(const std::string& s) : s(s) {};
std::string s;
~X() { std::cout << "Destroying: " << s << std::endl; }
private:
X(const X&) {};
X(X&&) {};
};
template <class T>
T&& id(T&& x) { return static_cast<T&&>(x); }
int main()
{
auto&& x1 = X("x1");
std::cout << "Line 1" << std::endl;
auto&& x2 = id(X("x2"));
std::cout << "Line 2" << std::endl;
}
However, I fear that in this case, x2 is a dangling reference, as X("x2")
is destroyed before "Line 2" executes.
So here, quite clearly id
has an observable effect.
How can I write an id
function in C++0x, which in particular works for types without move/copy constructors.
You can't. As a rule, you shouldn't write functions that return rvalue references- and as you pointed out correctly, you cannot extend the lifetime of the temporary long enough.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With