Efficiency difference between copy and move constructor

后端 未结 2 943
自闭症患者
自闭症患者 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条回答
  •  日久生厌
    2021-02-09 01:08

    First on your "understandings":

    As I can see it, they are in principle right but you should be aware of Copy elision which could prevent the program from calling any copy/move Constructor. Depends on your compiler (-settings).

    On your Questions:

    1. Yes you have to call foo(std::move(b)) to call an Function which takes an rvalue with an lvalue. std::move will do the cast. Note: std::move itself does not move anything.

    2. Using the move-constructor "might" be more efficient. In truth it only enables programmers to implement some more efficient Constructors. Example consider a vector which is a Class around a pointer to an array which holds the data (similar to std::vector), if you copy it you have to copy the data, if you move it you can just pass the pointer and set the old one to nullptr. But as I read in Effective Modern C++ by Scott Meyers: Do not think your program will be faster only because you use std::move everywere.

    3. That depends on the usage of the input. If you do not need a copy in the function it will in the most cases be more efficient to just pass the object by (const) reference. If you need a copy there are several ways of doing it for example the copy and swap idiom. But as a

提交回复
热议问题