C++ 在下面的代码中使用release和move的区别
我有一个狗类和一个uniqueptrholder 1和uniqueptrholder 2类,如下所示C++ 在下面的代码中使用release和move的区别,c++,C++,我有一个狗类和一个uniqueptrholder 1和uniqueptrholder 2类,如下所示 #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)
#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));
}
#包括
#包括
#包括
使用std::unique\u ptr;
使用std::string;
使用std::cout;
使用std::endl;
类狗{
公众:
Dog(string myName):name(myName){cout Usemove
,release
方法不会转移(可能不同的)删除程序。@user657267-这是回答的要点,除了@user657267指出的危险外,使用release()
在我看来,有人试图装出可爱的样子,只是为了让代码不那么可读。哪一个更能表达这里发生的事情,“移动”或“释放”?简短版本:如果你发现自己发布了unique\u ptr
以将所有权转移给另一个unique\u ptr
,你是在玩火,基本上沦为旧的auto\u ptr
,一个充斥着吮吸的想法最终被完全从标准库中删除。移动唯一指针;不要发布/重新获取可能重复的