Confusion with move constructors: cannot call constructor move

I am having difficulty understanding the movement of constructors in C ++. I created a simple class with a standard constructor, copy constructor, move constructor, and destructor. In addition, I defined a function with two overloads, one accepts a reference to this class, and one accepts an rvalue reference to this class. My test code is below.

#include <iostream>


class c {

public:

    c() {
        std::cout << "default constructor" << std::endl;
    }

    c(const c& s) {
        std::cout << "copy constructor" << std::endl;
    }

    c(c&& s) {
        std::cout << "move constructor" << std::endl;
    }

    ~c() {
        std::cout << "destructor" << std::endl;
    }

};

void f(c& s) {
    std::cout << "passed by reference" << std::endl;
}

void f(c&& s) {
    std::cout << "passed by rvalue reference" << std::endl;
}

int main() {

    c s1; // line 1
    std::cout << "\n";
    c s2(s1); // line 2
    std::cout << "\n";
    c s3(c()); // line 3

    std::cout << "\n";

    f(s1); // line 4
    std::cout << "\n";
    f(c()); // line 5

    getchar();
    return 0;

}

The output I get is not what I expected. Below is the output I get from this code.

default constructor

copy constructor

passed by reference

default constructor
passed by rvalue reference
destructor

, line 3. line 3, c s3(c());, c() r, , s3 . , . line 5 rvalue f(), , rvalue. .

: , c s3(std::move(c()));, rvalue s3? std::move?

+4
2

, 3, , , . , Most Vexing Parse.

c s3(c()) int foo(int ()), , , int foo(int (*f)()).

, ( ++ 11 ):

c s3(c{});

// or

c s3{c()};

// or

c s3{c{}};
+9

c s3(c()); . . s3, - c, - " c". , , .

, , c s3{c()};, , , .

+5

Source: https://habr.com/ru/post/1678423/


All Articles