C ++如何将对象移至nullptr [英] C++ how to move object to a nullptr
问题描述
我正在考虑一个奇怪的用例,我想将对象移至nullptr.也许我应该给一个代码片段:
I am thinking a strange use case where I want to move an object to a nullptr. Maybe I should give an code fragment:
class Objpair {
public:
Objpair(Obj&& a, Obj&&b) : first(&a), second(&b) { }
private:
Obj* first;
Obj* second;
};
问题在于,当a和b超出范围时,第一个和第二个指针将悬空.如果我可以将Object a移到第一个指针上,那么就不会有双重释放和作用域问题.如果首先将成员声明为Obj而不是Obj *指针,则直接的first(std :: move(a))将完成此工作.我在这里一定做错了.我正在考虑移动而不是复制,因为我试图将控制权从另一个对象转移到当前对象,并提高性能.
The problem is that when a and b is out of scope, the first and second pointer will be dangling. If I can move Object a onto the first pointer then there should be no problem of double free and scoping issues. If the member first were declared as Obj not Obj* pointer, then the straight first(std::move(a)) would do the job. I must be doing something wrong here. I am thinking of move instead of copying because I am trying to transfer of control from another object to the current object and improve on performance.
使用指针版本是因为我正在考虑成员对象的多态行为.
The pointer version is used because I am thinking about polymorphic behavior for the member object.
推荐答案
您可以做的是从您的参数中移动构造对象,如下所示:
What you can do is move construct objects from your parameters like this:
class Objpair {
public:
Objpair(Obj&& a, Obj&& b)
: first(new Obj(std::move(a)))
, second(new Obj(std::move(b)))
{}
private:
Obj* first;
Obj* second;
};
我建议您使用 std :: unique_ptr
:
class Objpair {
public:
Objpair(Obj&& a, Obj&& b)
: first(std::make_unique<Obj>(std::move(a)))
, second(std::make_unique<Obj>(std::move(b)))
{}
private:
std::unique_ptr<Obj> first;
std::unique_ptr<Obj> second;
};
这篇关于C ++如何将对象移至nullptr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!