c++ - Move constructor and pre-increment vs post-increment -
in c++, if have loop "copies" objects of user defined type using move constructor, make difference if use ++i
or i++
loop counter?
i know question seems rather vague, (i believe) asked in phone interview. wasn't sure if understood question correctly, , interviewer took not knowing answer, , cut interview short.
what have been getting at?
in c++, if have loop "copies" objects of user defined type using move constructor [...]
first of all, move constructor used move-constructing, means not "copying": can realize moving copying - in fact, class copy-constructible move-constructible - why defining move constructor explicitly?
[...] make difference if use ++i or i++ loop counter?
it depends on i
is. if scalar object, int
, there no difference @ all.
if i
class-type iterator, on other hand, ++i
should more efficient (on purely theoretical ground), because implementation of operator ++
not have create copy of iterator returned before iterator incremented.
here, instance, how stdlibc++ defines increment operators iterator type of std::list
:
_self& operator++() { _m_node = _m_node->_m_next; return *this; } _self operator++(int) { _self __tmp = *this; _m_node = _m_node->_m_next; return __tmp; }
as can see, postfix version (the 1 accepting dummy int
) has more work do: needs create copy of original iterator refurned, alter iterator's internal pointer, return copy.
on other hand, prefix version has alter internal pointer , return (a reference to) itself.
however, please keep in mind when performance concerned, assumptions have backed measurement. in case, not expect sensible difference between these 2 functions.
Comments
Post a Comment