我真的需要返回 Type::size_type 吗? [英] Do I really need to return Type::size_type?

查看:26
本文介绍了我真的需要返回 Type::size_type 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常有一些类,它们大多只是一些 STL 容器的包装器,如下所示:

I often have classes that are mostly just wrappers around some STL container, like this:

class Foo {
public:
  typedef std::vector<whatever> Vec;
  typedef Vec::size_type size_type;
  const Vec& GetVec() { return vec_; }
  size_type size() { return vec_.size() }
private:
  Vec vec_;
};

我不太确定是否返回 size_type.通常,某个函数会调用 size() 并将该值传递给另一个函数,而另一个函数将使用它并可能将其传递下去.现在每个人都必须包含那个 Foo 头,虽然我真的只是传递一些大小值,无论如何应该只是 unsigned int ......?在这里做什么是正确的?真正在任何地方都使用 size_type 是最佳实践吗?

I am not so sure about returning size_type. Often, some function will call size() and pass that value on to another function and that one will use it and maybe pass it on. Now everyone has to include that Foo header, although I'm really just passing some size value around, which should just be unsigned int anyway ...? What is the right thing to do here? Is it best practice to really use size_type everywhere?

推荐答案

STL 将这些类型定义为容器的抽象接口.它旨在支持任何类型的后备存储.这可能是 NUMA 或磁盘支持的存储,其中 size_typeptr-type 与系统内存的不同.或者 - 在 NUMA 架构中 - 它可能是一个特定的内存节点,速度很快,并且可以使用非常小的 size_typeptr_type - 这是对许多架构的相关优化.

STL defines these types as an abstract interface for containers. It is intended to support any type of backing storage. That might be NUMA or disk-backed storage, where size_type and ptr-type are different from those for system memory. Or - in a NUMA architecture - it might be a specific memory node that's fast, and can work with a very small size_type and ptr_type - which is a relevant optimization on many architectures.

至少,这是设计目标,也是由对支持 C++ 的平台可能的预期驱动的.一些早期的让步也为 STL 实现者提供了捷径,这些捷径基本上禁用了这种灵活性,而且我从未使用过利用这一点的 STL 实现.我会说这是因为线性内存访问已不再是一个问题,而且在该级别进行 STL 开发实际上并不容易.

At least, that were the design goals, also driven by anticipation what could be platforms supporting C++. Some early concessions also allowed shortcuts for STL implementers that basically disable this flexibility, and I've never worked with an STL implementation that made use of this. I'd say that's because linear memory access has become much less of a problem, and STL development at that level isn't actually easy.

不过,这对你有多大伤害?这是正确的做法.

Still, how much does it hurt you? It would be the right thing to do.

这篇关于我真的需要返回 Type::size_type 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆