为什么返回一个 int?

为什么 string::compare返回一个 int而不是像 shortchar这样的小型类型?我的理解是,这个方法只返回 -1、0或1。

第二部分,如果我要设计一个比较方法,比较两个 Foo类型的对象,并且我只想返回 -1、0或1,那么使用 shortchar通常是一个好主意吗?

编辑: 我已经更正,string::compare不返回 -1,0,或1,它实际上返回一个值 > 0,< 0或0。谢谢你们让我排队。

答案似乎是粗略的,没有理由返回一个小于 int的类型,因为返回值是“ rvalue”,而这些“ rvalue”不能从小于 int (4字节)的类型中获益。此外,许多人指出,大多数系统的寄存器大小可能是 int,因为这些寄存器将被填满,无论你给他们1,2或4字节的值,没有真正的优势,返回一个较小的值。

编辑2: 事实上,当使用诸如对齐、掩码等较小的数据类型时,似乎会有额外的处理开销。一般的共识是,存在较小的数据类型是为了在处理大量数据时节省内存,例如在处理数组时。

今天学到了一些东西,再次感谢大家!

8944 次浏览

if I was to design a compare method that compares two objects of type Foo and I only wanted to return -1, 0 or 1, would using short or char generally be a good idea?

It would be ok idea. A better way would be to return a bool (if only want to compare if equal), or enum (for more information) :

enum class MyResult
{
EQUAL,
LESS,
GREATER
};


MyResult AreEqual( const Foo &foo1, const Foo & foo2 )
{
// calculate and return result
}

First, the specification is that it will return a value less than, equal to or greater than 0, not necessarily -1 or 1. Secondly, return values are rvalues, subject to integral promotion, so there's no point in returning anything smaller.

In C++ (as in C), every expression is either an rvalue or an lvalue. Historically, the terms refer to the fact that lvalues appear on the left of an assignment, where as rvalues can only appear on the right. Today, a simple approximation for non-class types is that an lvalue has an address in memory, an rvalue doesn't. Thus, you cannot take the address of an rvalue, and cv-qualifiers (which condition "access") don't apply. In C++ terms, an rvalue which doesn't have class type is a pure value, not an object. The return value of a function is an rvalue, unless it has reference type. (Non-class types which fit in a register will almost always be returned in a register, for example, rather than in memory.)

For class types, the issues are a bit more complex, due to the fact that you can call member functions on an rvalue. This means that rvalues must in fact have addresses, for the this pointer, and can be cv-qualified, since the cv-qualification plays a role in overload resolution. Finally, C++11 introduces several new distinctions, in order to support rvalue references; these, too, are mainly applicable to class types.

Integral promotion refers to the fact that when integral types smaller than an int are used as rvalues in an expression, in most contexts, they will be promoted to int. So even if I have a variable declared short a, b;, in the expression a + b, both a and b are promoted to int before the addition occurs. Similarly, if I write a < 0, the comparison is done on the value of a, converted to an int. In practice, there are very few cases where this makes a difference, at least on 2's complements machines where integer arithmetic wraps (i.e. all but a very few exotics, today—I think the Unisys mainframes are the only exceptions left). Still, even on the more common machines:

short a = 1;
std::cout << sizeof( a ) << std::endl;
std::cout << sizeof( a + 0 ) << std::endl;

should give different results: the first is the equivalent of sizeof( short ), the second sizeof( int ) (because of integral promotion).

These two issues are formally orthogonal; rvalues and lvalues have nothing to do with integral promotion. Except... integral promotion only applies to rvalues, and most (but not all) of the cases where you would use an rvalue will result in integral promotion. For this reason, there is really no reason to return a numeric value in something smaller than int. There is even a very good reason not to return it as a character type. Overloaded operators, like <<, often behave differently for character types, so you only want to return characters as character types. (You might compare the difference:

char f() { return 'a'; }
std::cout << f() << std::endl;      //  displays "a"
std::cout << f() + 0 << std::endl;  //  displays "97" on my machine

The difference is that in the second case, the addition has caused integral promotion to occur, which results in a different overload of << to be chosen.

It's a C-ism.

When C required compare-type functions, they always returned an int. C++ just carried that forward (unfortunately).

However, returning an int is realistically probably the fastest way, as it's generally the size of the registers of the system in use. (Deliberately vague.)

Probably to make it work more like strcmp which also has this set of return values. If you wanted to port code it would probably be more intuitive to have replacements that cleave as close as possible.

Also, the return value is not just -1, 0 or 1 but <0, 0 or >0.

Also, as was mentioned since the return is subject to integral promotion it does not make sense to make it smaller.

The method doesn't actually return an integer in the set { -1, 0, 1 }; it can actually be any integral value.

Why? The main reason I can think of is that int is supposed to be the "natural size" value for the architecture; operations on values of this size are typically at least as fast (and in many cases faster) than operations on smaller or larger values. So this is a case of allowing the implementation enough slack to use whatever is fastest.

Suppose some people are changing a code from C to C++. They decided to replace strcmp to string::compare.

Since strcmp returns int, it's easier to string::compare return int, as a gift.

It is intentional that it doesn't return -1, 0 or 1.

It allows (note this is not for strings, but it applies equally to strings)

int compare(int *a, int *b)
{
return *a - *b;
}

which is a lot less cumbersome than:

int compare(int *a, int *b)
{
if (*a == *b) return 0;
if (*a > *b) return 1;
return -1;
}

which is what you'd have to do [or something along those lines] if you have to return -1, 0 or 1.

And it works for more complex types too:

class Date
{
int year;
int month;
int day;
}


int compare(const Date &a, const Date &b)
{
if (a.year != b.year) return a.year - b.year;
if (a.month != b.month) return a.month - b.month;
return a.day - b.day;
}

In the string case, we can do this:

int compare(const std::string& a, const std::string& b)
{
int len = min(a.length(), b.length());


for(int i = 0; i < len; i++)
{
if (a[i] != b[i]) return a[i] - b[i];
}
// We only get here if the string is equal all the way to one of them
// ends. If the length isn't equal, "longest" wins.
return a.length() - b.length();
}

because a boolean return value can only be two possible values (true, false), and a compare function can return three possible values (less than, equal, greater than).

Update

While certainly possible to return a signed short, if you really wanted to implement your own compare function, you could return a nibble or struct value with two booleans.

int is usually (meaning on most modern hardware) an integer of the same size as the system bus and/or the cpu registers, what is called the machine word. Therefore int is usually passed along faster than smaller types, because it doesn't require alignment, masking and other operations.

The smaller types exist mainly to allow RAM usage optimization for arrays and structs. In most cases they trade a few CPU cycles (in the form of aligment operations) for a better RAM usage.

Unless you need to enforce your return value to be a signed or unsigned number of a centain size (char, short…) your are better off using int, which is why the standard library does it.