如何过早销毁智能指针
How to destroy a smart pointer prematurely
我有一个 class,它有一个 setter 方法,该方法将 unique_ptr 作为参数。 unique_ptr 被保存为 class 成员。
class TestClass {
std::unique_ptr<Tester> sp;
void setTester_Way1(std::unique_ptr<Tester> te) {
auto deleter=std::move(sp);
sp=std::move(te);
}
void setTester_Way2(std::unique_ptr<Tester> te) {
sp=std::move(te);
}
};
智能指针的正确设置方式是什么? Way2是否泄露了sp的原始指针?
方法 2 很好,当您分配给 unique_ptr
时,任何现有的拥有指针都将被安全删除。
正如Chris Drew所说,Way2很好。不过有一件事是 unique_ptr
不是 copyable/assignable,因此传递 unique_ptr
的唯一方法是通过引用、右值引用或通过 move()
的值。尝试做:
int main()
{
TestClass t;
auto p = std::make_unique<int>(10);
t.setTester_Way2(p);
}
Will fail to compile. Although you can move()
p
into the function(example).
如果把setTester_Way2()
改成void setTester_Way2(std::unique_ptr<int>& te)
then it will compile。如果您将函数更改为采用右值引用和 std::move()
指向函数的指针:
class TestClass {
std::unique_ptr<int> sp;
public:
void setTester_Way1(std::unique_ptr<int> te) {
auto deleter=std::move(sp);
sp=std::move(te);
}
void setTester_Way2(std::unique_ptr<int>&& te) {
sp=std::move(te);
}
};
int main()
{
TestClass t;
auto p = std::make_unique<int>(10);
t.setTester_Way2(std::move(p));
}
我有一个 class,它有一个 setter 方法,该方法将 unique_ptr 作为参数。 unique_ptr 被保存为 class 成员。
class TestClass {
std::unique_ptr<Tester> sp;
void setTester_Way1(std::unique_ptr<Tester> te) {
auto deleter=std::move(sp);
sp=std::move(te);
}
void setTester_Way2(std::unique_ptr<Tester> te) {
sp=std::move(te);
}
};
智能指针的正确设置方式是什么? Way2是否泄露了sp的原始指针?
方法 2 很好,当您分配给 unique_ptr
时,任何现有的拥有指针都将被安全删除。
正如Chris Drew所说,Way2很好。不过有一件事是 unique_ptr
不是 copyable/assignable,因此传递 unique_ptr
的唯一方法是通过引用、右值引用或通过 move()
的值。尝试做:
int main()
{
TestClass t;
auto p = std::make_unique<int>(10);
t.setTester_Way2(p);
}
Will fail to compile. Although you can move()
p
into the function(example).
如果把setTester_Way2()
改成void setTester_Way2(std::unique_ptr<int>& te)
then it will compile。如果您将函数更改为采用右值引用和 std::move()
指向函数的指针:
class TestClass {
std::unique_ptr<int> sp;
public:
void setTester_Way1(std::unique_ptr<int> te) {
auto deleter=std::move(sp);
sp=std::move(te);
}
void setTester_Way2(std::unique_ptr<int>&& te) {
sp=std::move(te);
}
};
int main()
{
TestClass t;
auto p = std::make_unique<int>(10);
t.setTester_Way2(std::move(p));
}