Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I really need to return Type::size_type?

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_;
};

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?

like image 232
Frank Avatar asked Dec 01 '22 10:12

Frank


2 Answers

It should be vector<>::size_type like you have, this is the most correct way.

That said, I know many people, including myself, will just use size_t instead. Although it's not mandated to be the same, vector<>::size_type is size_t for every implementation I know. You should be fine with that.

like image 168
GManNickG Avatar answered Dec 04 '22 01:12

GManNickG


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.

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.

like image 30
peterchen Avatar answered Dec 04 '22 02:12

peterchen