Efficiency difference between copy and move constructor

后端 未结 2 948
自闭症患者
自闭症患者 2021-02-09 00:29

C++11 introduced a new concept of rvalue reference. I was reading it somewhere and found following:

class Base
{
public:
    Base()  //Default Ctor
    Base(int          


        
2条回答
  •  猫巷女王i
    2021-02-09 00:51

    Line 2 before C++11 would have called copy constructor and all those temporary copy stuff, but with move constructor defined, that would be called here.

    Correct, except any decent optimizer would "elide" the copy, so that before C++11 the copy would have been avoided, and post C++11 the move would have been avoided. Same for line 3.


    1. I know once we move an object it's data will be lost at calling location.

    Depends on how the move constructor/assignment is implemented. If you don't know, this is what you must assume.

    So, i above example how can i change Line 2 to move object "b" in foo (is it using std::move(b) ?).

    Exactly. std::move changes the type of the expression into r-value and therefore the move constructor is invoked.

    I have read move constructor is more efficient than copy constructor.

    It can be, in some cases. For example the move constructor of std::vector is much faster than copy.

    I can think of only situation where we have memory on heap need not to be allocated again in case of move constructor. Does this statement hold true when we don't have any memory on heap?

    The statement isn't universally true, since for objects with trivial copy constructor, the move constructor isn't any more efficient. But owning dynamic memory isn't strictly a requirement for a more efficient move. More generally, move may can be efficient if the object owns any external resource, which could be dynamic memory, or it could be for example a reference counter or a file descriptor that must be released in the destructor and therefore re-aquired or re-calculated on copy - which can be avoided on move.

    Is it even more efficient than passing by reference (no, right?)?

    Indeed not. However, if you intend to move the object within the function where you pass it by reference, then you would have to pass a non-const reference and therefore not be able to pass temporaries.

    In short: Reference is great for giving temporary access to an object that you keep, move is great for giving the ownership away.

提交回复
热议问题