[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 376
  • Last Modified:

STL

Why prefix is better than postfix in STL?
0
t55555
Asked:
t55555
1 Solution
 
prashant_n_mhatreCommented:
Consider a loop:

for(int count = 0; count < 10; count++)
{
}
 
This is fine when the variable are basic types, but I think this is a good habit to get out of when you use STL...Take the example of these two iterator loops:

std::list<Object> aList;

for(std::list<Object>::iterator iter = aList.begin(); iter != aList.end();
iter++)
{
}

for(std::list<Object>::iterator iter = aList.begin(); iter != aList.end();
++iter)
{
}
 
A subtle difference, but a big one... Let's see how the pre and postfix operators are defined in the Microsoft implementation...(I guess many people use this..), and it's fairly representative of how many implementations work. The first function is the postfix operator and the later is the prefix operator.

iterator operator++(int)
{
     iterator _Tmp = *this;
     ++*this;
     return (_Tmp);
}

iterator& operator++()
{
     _Ptr = _Acc::_Next(_Ptr);
     return (*this);
}
 
Because postfix operations must occur after any operations, it must make a copy of the object it's operation on first to preserve the original state of the object. This means the copy constructor gets invoked on the object, and this can be very expensive if something like a string copy is involved, and is generally a waste of valuable instructions. For that matter, it winds up calling the prefix operator anyway... The prefix operator doesn't have to worry about the data changing, so it's free to do what it wants, which is to just set the iterator to point to the next object in the list.

Hence the moral of the story is... "Unless you absolutely need to use postfix, get in the habit of using prefix."
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now