将unique_ptr分配给原始指针
Assigning a unique_ptr to a raw pointer
我正在尝试使用唯一的指针将一个节点链接到另一个节点。我设法用下面的代码做到了,但它感觉像是糟糕的代码,因为它太长了.我怎样才能改善这一点?
#include <memory>
#include <iostream>
using namespace std;
template<typename T>
class Node {
public:
T data;
unique_ptr<Node<T>> nextNode;
Node(T dataIn) : data(dataIn), nextNode(nullptr) {
}
void setNextNode(Node<T> * nodeIn) {
unique_ptr<Node<T>> newNextNode(nodeIn);
nextNode = std::move(newNextNode);
}
void printData() {
cout << data << endl;
}
};
int main() {
unique_ptr<Node<int>> root(new Node<int>(26));
Node<int> * nodeTwo = new Node<int>(88);
root->setNextNode(nodeTwo);
}
也许使用右值引用和交换移动:
#include <memory>
#include <iostream>
using namespace std;
template<typename T>
class Node {
public:
T data;
unique_ptr<Node<T>> nextNode;
Node(T dataIn) : data(dataIn), nextNode(nullptr) {
}
void setNextNode(std::unique_ptr<Node<T>> &&nodeIn) {
std::swap(nextNode, nodeIn);
}
void printData() {
cout << data << endl;
}
};
int main() {
unique_ptr<Node<int>> root(new Node<int>(26));
root->setNextNode(std::make_unique<Node<int>>(88));
root->nextNode->printData();
}
简短的评论是,您不应该传达来自其他 palces 的unique_ptrs作为显示所有权的全部意义,所以有人说更改 setNextNode:
void setNextNode(T &&nodeValue) {
nextNode = std::make_unique<Node<T>>(nodeValue);
}
并像这样添加:
root->setNextNode(88);
此外,make_unique是 c++14 的一部分,如果您正在使用 c++11,请使用 reset:
nextNode.reset(new Node<T>(nodeValue));
这不是使用unique_ptr
s 的推荐方式:您可以使用std::make_unique
,而不是使用new
创建对象,它会自动将对象包装在一个唯一的指针中。
您还混合了原始指针和唯一指针,这很糟糕,因为它可能会导致混淆谁是传递对象的所有者。下面是一个更好的列表示例:
#include <memory>
#include <iostream>
template<typename T>
class Node {
public:
T data;
std::unique_ptr<Node<T>> nextNode = nullptr;
Node(T dataIn) : data(dataIn) {
}
void setNextNode(std::unique_ptr<Node<T>>&& nodeIn) {
std::swap(nextNode, nodeIn);
}
void printData() {
std::cout << data << std::endl;
}
};
int main() {
auto root = std::make_unique<Node<int>>(26);
auto nodeTwo = std::make_unique<Node<int>>(88);
root->setNextNode(std::move(nodeTwo));
}
请注意使用std::move
和std::swap
来正确转让所有权。
相关文章:
- 从堆栈分配的原始指针构造智能指针
- 将unique_ptr分配给原始指针
- 如何将唯一指针的 std::vector 转换为原始指针的 std::span?
- <Base> <Derived> 具有相同原始指针共享引用的 shared_ptr 和 shared_ptr 实例是否计数?
- C++原始指针和"delete"
- 为什么 C++ 地址中的矢量无法通过原始指针访问
- 如何正确实现具有原始指针的类的复制构造函数?
- 如何在将原始指针移动到基类构造函数之前从unique_ptr中提取原始指针
- 为包含原始指针的对象C++智能指针
- c++:复制、删除和运算符=在原始指针映射中
- C++模板,用于通过常量引用和原始指针传递向量
- C++为什么原始指针不会增加shared_ptr的引用计数?
- 从shared_ptr获取原始指针以将其传递给需要 raw 的函数
- 如何包装多级原始指针以赋予其容器语义
- 为什么我可以通过原始指针而不是shared_ptr来修改对象
- 将原始指针传递给接受unique_ptr作为参数的函数
- 为什么我们不允许将纯引用参数传递给 std::thread,但允许传递原始指针?
- 更改保留指向其字段的原始指针的对象地址
- 从原始指针(衰减的 C 样式数组)和大小生成范围::视图
- 如何在C++代码中灵活使用和替换标准::shared_ptr或标准::unique_ptr或原始指针?