LeetCode Note: ++i or i++

It's quite funny that there is a very apparent question but few people care about. That is the difference between the '++i' and the 'i++'. The first time that I found this question was when I saw the code example on the cplusplus.com which used '++i' every time they wanted to construct a for loop.  So below are the answer to this question provided by someone on the StackOverflow:

[Executive Summary: Use ++i if you don't have a specific reason to use i++.]

For C++, the answer is a bit more complicated.

If i is a simple type (not an instance of a C++ class), then the answer given for C ("No there is no performance difference") holds, since the compiler is generating the code.

However, if i is an instance of a C++ class, then i++ and ++i are making calls to one of the operator++ functions. Here's a standard pair of these functions:

Foo& Foo::operator++()   // called for ++i
{
    this->data += 1;
    return *this;
}

Foo Foo::operator++(int ignored_dummy_value)   // called for i++
{
    Foo tmp(*this);   // variable "tmp" cannot be optimized away by the compiler
    ++(*this);
    return tmp;
}

Since the compiler isn't generating code, but just calling an operator++ function, there is no way to optimize away the tmp variable and its associated copy constructor. If the copy constructor is expensive, then this can have a significant performance impact.



猜你喜欢

转载自blog.csdn.net/shit_kingz/article/details/79993944
i++