Search code examples
c++c++11rvalue-referencetemporary

Distinguish between temporaries and non-temporaries in function signature?


I want to create a class Bar that can distinguish between temporaries and non-const non-temporaries. According to this (about 25% down the page), I can get away with this if the second StealPointer takes a const reference (to a pointer in my case), but in my code it just uses the StealPointer(Foo*&& foo) version regardless of how it is called.

class Foo {};

class Bar {
 public:
  // For when StealPointer(new Foo()); is called. Bar instance then owns the
  // pointer.
  void StealPointer(Foo*&& foo) {} // Get the temporaries only.

  // For when a Foo* already exists and is passed in StealPointer(my_foo_ptr);
  // Takes ownership and invalidates the pointer that the caller once had.
  void StealPointer(Foo*&) {} // Get lvalues only.
};

Can I do this? Is there a way to do this that only requires one function? If it matters, Bar is going to store the pointer in a unique_ptr and I would like to avoid the additional syntax of passing in a unique_ptr or making the caller do something with std::move. I can't just pass the pointers by reference, because temporaries of type Foo* can't be converted to Foo*&.


Solution

  • Make your function templated and let std::unique_ptr worry about those details for you.

    template <typename Ptr>
    void StealPointer(Ptr&& p) // a universal reference, matches *any* type of value
    {
        uniqptr = std::move(p); // Works for both rvalues and lvalues
    }