3

I have a dog class and a UniquePtrHolder1 and UniquePtrHolder2 classes as below

#include <memory>
#include <string>
#include <iostream>

using std::unique_ptr;
using std::string;
using std::cout;
using std::endl;

class Dog {    
public:
    Dog(string myName) : name(myName) { cout << "Dog is created " << name.c_str()  << endl; }

private:
    string name;
};

class UniqePtrHolder1 {
public:     
    UniqePtrHolder1(unique_ptr<Dog> dog) : m_dog(std::move(dog)) {}; 
    unique_ptr<Dog> m_dog;
};

class UniqePtrHolder2 {
public:

    UniqePtrHolder2(unique_ptr<Dog> dog) : m_dog(dog.release()) {}    
    unique_ptr<Dog> m_dog;
};

int main()
{
 unique_ptr<Dog> pD1(new Dog("Gunner"));
 UniqePtrHolder1 holder1(std::move(pD1));

 unique_ptr<Dog> pD2(new Dog("Hunter"));
 UniqePtrHolder2 holder2(std::move(pD2));


}

In the above code UniqePtrHolder1 class uses the move constructor of the dog to initilaize its Dog while UniqePtrHolder2 uses the release method of the unique pointer to initialize its Dog. Both methods works fine.

When I was studying some code, I saw both these implementations at different places. Is there any reason to use one over the other. Performance wise are they both the same ?

3mr
  • 312
  • 2
  • 16
  • 9
    Use `move`, the `release` method won't transfer the (potentially different) deleter. – user657267 Dec 13 '18 at 06:37
  • 1
    @user657267 - That's the gist of an answer – StoryTeller - Unslander Monica Dec 13 '18 at 06:39
  • 3
    Aside from being dangerous as @user657267 points out, using `release()` here strikes me as someone trying to be cute, only to make the code less readable. Which better expresses what's happening here, "move" or "release"? – TypeIA Dec 13 '18 at 06:39
  • Short version: If you find yourself releasing `unique_ptr` to transfer ownership to another `unique_ptr`, you're playing with fire, and basically relegating to the old `auto_ptr`, an idea so riddled with suck it was eventually removed from the standard library entirely. *Move* unique pointers; don't release/reacquire them. – WhozCraig Dec 13 '18 at 06:46
  • possible duplicate of https://stackoverflow.com/questions/36030464/stdunique-ptrrelease-vs-stdmove – P.W Dec 13 '18 at 07:00
  • Possible duplicate of [std::unique\_ptr::release() vs std::move()](https://stackoverflow.com/questions/36030464/stdunique-ptrrelease-vs-stdmove) – Toby Speight Oct 03 '19 at 08:37

0 Answers0