简体   繁体   English

int vs无符号int vs size_t

[英]int vs unsigned int vs size_t

Starting with a more advanced C++ course, we have to implement an own Matrix, which is typical for first exercises. 从更高级的C ++课程开始,我们必须实现自己的矩阵,这对于首次练习来说是典型的。 We received a skeleton to work on and i have got only one question left. 我们收到了要处理的基本信息,我只剩下一个问题。 The type of the access and size variables. 访问类型和大小变量。

Here a simple constructor for 1D Matrix, with some Checking of the size. 这里是1D矩阵的简单构造函数,并进行了大小检查。

Array::Array( int xSize )                                                                                     
{                   
    CHECK_MSG(xSize > 0, "Array size too small");
    array_ = new real[xSize];
    size_ = xSize;  
}

Does it make sense to use a size_t or unsigned int instead of an int? 使用size_t或unsigned int代替int是否有意义? After reading the definition of size_t i would tend to use it instead. 阅读size_t的定义后,我倾向于改用它。 However in many codes i see just ints everywhere. 但是,在许多代码中,我到处都只能看到整数。 Is it a java-like coding style? 它是一种类似Java的编码风格吗? Has size_t any disadvantages i missed? 我错过了size_t的缺点吗?

Edit: 编辑:

The main question relates to the coding style. 主要问题与编码风格有关。 I fully understand the difference of size_t and (unsigned) int, as it was already explained here: unsigned-int-vs-size-t 我完全理解size_t和(unsigned)int的区别,正如这里已经解释过的: unsigned-int-vs-size-t

The C++ standard library would almost certainly use a std::size_t for such a type. C ++标准库几乎可以肯定将std::size_t用于此类类型。

Using a signed type is obviously not desirable and, ideally, you want to use a type that lends itself well to having an object that supports iterability. 使用带signed类型显然是不希望的,并且理想情况下,您希望使用一种非常适合于拥有支持可迭代性的对象的类型。

From the outset I recommend you use typedef std::size_t MySize; 从一开始我建议您使用typedef std::size_t MySize; within your class, mainly to future-proof yourself. 在课堂上,主要是为了适应未来。 That would be the most sensible choice. 那将是最明智的选择。

Can the size of anything ever be negative? 事物的大小可以为负吗? No, so use unsigned for xSize to express the intent of the code more explicitly. 否,因此对xSize使用unsigned可以更明确地表达代码的意图。

If you need it be able to handle really big sizes, use size_t . 如果您需要能够处理很大的尺寸,请使用size_t

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM