LoS*_*LoS 2 c++ unordered-map stdmap unique-ptr c++17
阅读节点句柄的文档,我注意到节点句柄类型的许多功能可以简单地通过std::unique_ptr. 事实上,节点句柄类型的功能与std::unique_ptr. 它只有一个更符合关联容器特性的接口,例如key_type和mapped_type别名以及获取键/映射值引用的函数。
std::unique_ptr因此,与as的简单特化相比,该标准引入了节点句柄类型,还有其他优点吗node_type?
从纯粹的哲学角度来看,仅仅因为一种类型与另一种类型具有相似的接口并不意味着该类型是多余的并且应该被更通用的类型取代。
在这种特殊情况下,类型并不等同。主要目标之一node_handle是您不知道容器使用的节点的实际类型。甚至不能作为不透明的类型别名;node_type是 的特化node_handle,而不是内部节点类型名。
另外,考虑一下unique_ptr,就其本质而言,包装了一个指向某物的指针。有一个指针在某个时刻不被拥有,然后unique_ptr拥有它。因此,release是一个合理的函数:它否认指针而不破坏它。
That's not a reasonable function for node_handle. You did not create that node, and therefore you're not equipped to destroy it. That node is owned by a system that is intentionally opaque to the user. Any pointer held by it points to implementation-defined data structures, and there may be more than one of them.
But that ignores the key feature of node_handle, the reason why it exists at all. The point of a node_handle is that you can extract an element from such a container, modify its key (and thus affecting where it would go in the container), and then reinsert it without allocating memory. To do that with unique_ptr<T> would require that T be some type the user understands and can talk to (and therefore used to modify the key). So, what is T?
It can't be value_type for the container, as that makes the key type const and therefore non-modifiable. So it has to be some new type that gives you an interface to modify the key's value. Since it has to be some new type anyway... you may as well just make node_handle that type and save yourself a bunch of pain.
Also, there is allocator behavior to consider. First, a node_handle also stores a copy of the container's allocator. Which unique_ptr can't really do.
Second, stateful allocators may have special behavior when you move-assign from one container to another. Specifically, you may need to move the allocator when you do. But for many allocators, you may not. Therefore, node_handle needs to replicate this behavior. unique_ptr can't do that either.
Now, you could essentially achieve all of this by creating a specialization of unique_ptr with a different interface conforming to the above, through the use of hidden (container-specific) typenames as template parameters. But... why bother? It's a different interface with a different, specialized purpose.
So give it its own typename already. C++ is not running out of names.
| 归档时间: |
|
| 查看次数: |
127 次 |
| 最近记录: |