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 ?