C++: impliziter move

Diese Seite verwendet Cookies. Durch die Nutzung unserer Seite erklären Sie sich damit einverstanden, dass wir Cookies setzen. Weitere Informationen

  • C++: impliziter move

    Hallo.
    Ich hatte immer gedacht, dass C++ für Rvalues die an eine Funktion übergeben werden, die ihre Argumente by value annimmt, ebenfalls eine Kopie anlegt.
    Doch scheinbar ist dies nicht der Fall.

    Etwas Code um das ganze zu verdeutlichen:

    Quellcode

    1. #include <iostream>
    2. struct A {public: int id; bool copy;
    3. explicit A() : id(42) { std::cout << "CTor: " << id << std::endl;
    4. copy = false; }
    5. A(int val) : id(val) { std::cout << "CTor: " << id << std::endl;
    6. copy = false; }
    7. A(const A& a) { std::cout << "Copy CTor" << std::endl;
    8. copy = true; id = a.id * 2; }
    9. A(const A&& a) { std::cout << "Move" << std::endl;
    10. id = a.id; copy = false; }
    11. ~A() { if (copy) std::cout << "Copy "; std::cout << "DTor: " << id << std::endl; }};
    12. void foo(A a) { std::cout << "foo says " << a.id << std::endl;}
    13. int main() { A a; foo(a); std::cout << "====" << std::endl; foo(A(23)); std::cout << "end of main" << std::endl;}
    Alles anzeigen



    Ich hatte mit folgender Ausgabe gerechnet:


    CTor: 42
    Copy CTor
    foo says 84
    Copy DTor: 84
    ====
    CTor: 23
    Copy CTor
    foo says 46
    Copy DTor: 46
    end of main
    DTor: 42
    DTor: 23



    doch ich bekomme diese:


    CTor: 42
    Copy CTor
    foo says 84
    Copy DTor: 84
    ====
    CTor: 23
    foo says 23
    DTor: 23
    end of main
    DTor: 42


    Also moved der Compiler den Aufruf A() in den Funktionsstack von foo oder was geht da von statten? Und wie heißt dieses Verfahren?