C++ 更改unique_ptr指向的指针是否为未定义行为?

C++ 更改unique_ptr指向的指针是否为未定义行为?,c++,pointers,unique-ptr,C++,Pointers,Unique Ptr,对通过get获取的唯一_ptr的原始指针执行重置是未定义的行为,如下所示: std::unique_ptr<int> thing(new int(8)); int* other = thing.get(); other.reset(new int(15)); 但是,如果unique_ptr的原始指针可以指向相同类型的对象呢?例如,给定以下代码 class Node { public: std::unique_ptr<Node>

对通过get获取的唯一_ptr的原始指针执行重置是未定义的行为,如下所示:

   std::unique_ptr<int> thing(new int(8));
   int* other = thing.get();
   other.reset(new int(15));
但是,如果unique_ptr的原始指针可以指向相同类型的对象呢?例如,给定以下代码

class Node {
    public:
        std::unique_ptr<Node> previous;
        std::unique_ptr<Node> next;
        int data;        
        Node(int d) : previous(nullptr),
                      next(nullptr),   
                      data(d) {}
};

void some_function(std::unique_ptr<Node> node, Node* other_ptr) {
    Node* node_ptr = node.get();
    node_ptr->next.reset(other_ptr); // ***           
    ………………………………………………………………………………….
    ………………………………………………………………………………….
   // Some code. Please don't focus on the secondary things.
   // The main question whether it allowed to perform reset from line ****)
}
这也是未定义的行为吗?如果是,为什么


代码链接:

在以下前提下,某些函数的行为得到了很好的定义:

其他ptr必须已使用new分配,并且仍然有效,不能删除。 其他ptr的所有权必须已转移1至职能部门,即其他任何部门均不拥有该ptr。 节点不能为null。 然而,和所有参数一样,节点是函数的局部变量。当函数结束时,节点被销毁。因此,它管理的指针将被删除。因此,修改指针对象似乎毫无意义,函数就是这样做的

1使用裸指针转移所有权是个坏主意。您应该改为使用唯一指针来转移所有权

另外,使用下一个和上一个指针,节点看起来很像一个双链接列表。但是,它不能是列表,因为前一个节点和下一个节点不可能同时拥有当前节点的唯一所有权


p.p.S.节点*Node_ptr=Node.get;节点\u ptr->下一步。重置。。。可以简化为节点->下一步。重置。

您不能这样做。在原始指针上重置。这不是未定义的行为,而是编译错误。除了废话,我认为答案取决于anytone是否拥有其他\u ptr。目前您正在使用resetother\u ptr声明它的所有权,因此最好不要在其他任何地方拥有它。@std\u name Heres:int*other。。。other.reset…@std:您的示例代码生成:…\main.cpp:7:12:错误:请求“other”中的成员“reset”,这是非类类型的“int*”,我认为您非常误解了unique\ptr。当您将node by value传递给某个函数时,它将被销毁,并且该函数中包含的指针将被删除。node_ptr->next是完全多余的,可以用node->next替换。另外,有些函数声明返回`Node*,但没有返回语句。谢谢您的回答