C++将unqiue_ptr与同一对象的原始指针混合在一起
C++ mixing unqiue_ptr with raw pointer for the same object
我一直在用算法练习一些练习来学习 c++。我正在编写一个单词trie,并考虑了一个解决方案,将unique_ptr与同一对象的原始指针混合在一起。我看了一堂讲座,演讲者正在讨论不要过度使用unique_ptr和shared_ptr。他们还提到,只要没有隐含所有权,原始指针就很好。我相信这可以通过另一种方式实现,但我想了解是否有我没有看到的问题。据我所知,这是一种常见的做法,或者你能做的最愚蠢的事情。这是一些课程。
class node {
public:
node(node * parent) :
parent { parent } {
}
void insert(const std::string & word, int index) {
auto c = word[0];
if (children[c-'a'] == nullptr) {
children[c-'a'] = std::make_unique(this);
}
if(!word.size()>1) {
children[c-'a']->tnsert(word.substr(1), index);
}
else {
occurrences.push_back(index);
}
}
std::unique_ptr<node> & find(const std::string & word) const {
auto c = word[0];
if (children[c-'a'] != nullptr) {
if(!word.size()>1) {
return children[c-'a']->find(word.substr(1);
}
else {
return children[c-'a'];
}
}
return nullptr;
}
private:
node * parent;
std::vector<std::unique_ptr<node>> children(26);
};
我选择将向量中的节点作为unique_ptrs,原因有两个 内存和空插槽在算法中具有重要意义。在创建子项时的插入方法中,我在其构造函数中使用了this。我什至认为 find 方法可以使用原始指针实现,例如:
node * find(const std::string & word) const;
我只需要添加一个像节点 * get_raw() { 返回这个; } 这样的成员,而不是像unique_ptr那样返回孩子,只需返回 get_raw();。我知道有很多方法可以以不同的方式编码。我本可以使用std::unique_ptr和parent。原始指针对于没有父节点的根节点来说更容易。
你的unique_ptrs
vector
是合法的,一个好处是你可以调用children.clear(),
,每个指针都会被正确删除。
仅当要修改unique_ptr
对象时,才应返回unique_ptr& or unique_ptr*
。
与使用 get()
返回原始指针相比,返回unique_ptr
没有任何好处,因为在一天结束时,您需要test
在这两种情况下nullptr
。
此外,您的查找函数未正确编写:
std::unique_ptr<node> & find(const std::string & word) const {
auto c = word[0];
if (children[c-'a'] != nullptr) {
if(!word.size()>1) {
return children[c-'a']->find(word.substr(1);
}
else {
return children[c-'a'];
}
}
// nullptr will be converted to a local unique_ptr object. you cannot
// return a reference to a local object that's about to be destroyed.
// return nullptr;
static const std::unique_ptr<node> empty;
return empty;
}
// Or
node* find(const std::string & word) const
{
return children[c-'a'].get();
}
相关文章:
- C ++引用函数参数似乎包含原始对象的副本,而不是充当"real reference"
- 为包含原始指针的对象C++智能指针
- 为什么我可以通过原始指针而不是shared_ptr来修改对象
- 更改保留指向其字段的原始指针的对象地址
- 如何在C++中将类的实例完全重新分配给同一类的另一个实例(然后删除原始对象)?
- 是否可以反序列化(从原始内存块)没有默认构造函数的对象?
- 当原始指针和唯一指针都引用同一对象时,如何避免双重释放
- 如何从 GDI+ 图元文件对象获取原始图元文件字节
- 指向同一对象的多个原始指针
- C++修改通过引用传递的类不会更改原始对象
- 在保持原始对象的同时移动
- 在原始对象上使用惯用(例如 TBB 的 thread_enumerable_specific')移动赋值调用析构函数
- 将原始指针向量清除给由独特指针拥有的对象
- 操作员重载=修改原始对象
- 将新对象shared_pt分配给 A[1],则 A[1] 中包含的原始对象的引用计数减少.如何
- 是否可以按值传递临时对象而不破坏C++中的原始对象
- 从数据库中以 blob 数据类型形式存储的原始图像数据中检索 CImage 对象
- VTK ActiViz将对象重置为原始视图
- C++将unqiue_ptr与同一对象的原始指针混合在一起
- 基类类型的指针忘记了原始对象类型