将普通指针类型转换为unique_ptr类型是一种不好的做法吗?
Is Typecasting a normal pointer to a unique_ptr a bad practice?
我使用unique_ptr
和普通指针的混合实现了一个单链表。
我有这样的代码:
template<typename B>
void linkedlist<B>::addNode(B x){
node * n = new node; //initialize new node
n->x = x;
n->next = nullptr; //smart pointer
if(head == nullptr){ //if the list is empty
head = (unique_ptr<node>)n; //cast the normal pointer to a unique pointer
}else{ //if there is an existing link
current = head.get(); //get the address that is being
//pointed by the unique_ptr head
while(current->next != nullptr) //loop until the end then stop
current = (current->next).get();
current->next = (unique_ptr<node>) n; //connect the new node to the last node
}
}
我听说这是一个不好的做法,如果是这样,谁能告诉我为什么?如有任何建议或建议,请参考。
虽然强制转换语法有点奇怪,但它完全等同于更常规的
unique_ptr<node>(n)
本身并不是一个坏习惯。糟糕的做法是让原始指针一直挂在那里,如果存在既不删除原始指针也不将其传输到智能指针的代码路径,则存在泄漏的危险。
你应该从
开始unique_ptr<node> n(new node);
并通过移动它来转移所有权
head = std::move(n);
在您的情况下,这可能不是问题,但是将现有的原始指针转换为unique_ptrs是一种不好的做法,主要是因为涉及到语义。当Unique_ptr超出作用域时,将运行delete。
考虑以下
int ptr_method(int * i) {
auto a = (unique_ptr<int>)i;
return *a.get();
}
int main() {
int i = 10;
ptr_method(&i);
}
当ptr_method
返回时,i
会发生什么?
相关文章:
- 在运行时检查继承是否只有一种类型和 void*
- 另一种类型的智能ptr,比如具有弱refs的unique_ptr
- void* 数组将元素转换为另一种类型
- 将一种类型的比特重新解释为不同类型的比特的技术
- 将 X 坐标从一种分辨率转换为另一种分辨率
- 为什么需要类型名称,即使似乎足以推断名称应该是一种类型?
- 在 c++ 中将一种结构类型分配给另一种类型
- 将空基类优化对象强制转换为另一种类型是否会破坏严格的别名?
- 我怎样才能让编译器推导出一种类型的 nullptr
- 将 32 位浮点数和不强制转换的 32 位整数与双精度进行比较,当其中一个值可能太大而无法完全适合另一种类型时
- 自动将一种 c++ 类型转换为另一种
- 是否可以将一种类型的数组转换为大小不同的另一种类型的数组?
- 在比较中使用已强制转换为另一种类型的函数指针是否定义良好?
- 如何使用模板元编程在 C++17 中将一种类型转换为另一种类型
- 将"this"指针强制转换为另一种类型不违反严格锯齿?
- 防止将对象强制转换为除一种类型C++之外的任何类型
- C++ 为什么我们需要从一种类型显式转换为另一种类型
- 从一种类型转换为另一种类型的错误
- 从一种类型转换为另一种类型时的模板类型扣除
- 为什么 c++ 在尝试将字符串转换为另一种类型时无法识别字符串?