Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"id" function in C++0x

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.

like image 732
Clinton Avatar asked Aug 23 '11 14:08

Clinton


1 Answers

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.

like image 140
Puppy Avatar answered Nov 12 '22 06:11

Puppy