search

Home  >  Q&A  >  body text

c++移动构造函数什么时候会被调用?

class x{
public:
    x( moveClass&& item) {
        std::cout << 123 << std::endl;
    }
    
    x() = default;
};


int main(){
    x(x());
}

如上的代码, 不应该输出123吗, 为什么什么都没有输出... 这种情况到底算调用了哪种构造方法.

黄舟黄舟2806 days ago664

reply all(3)I'll reply

  • 大家讲道理

    大家讲道理2017-04-17 14:34:10

    Your code should not output 123. That's a function declaration, it doesn't call x(moveClass&& item). My understanding is that the move constructor is used on rvalues ​​to reduce calls to temporary constructors and destructors. When you use rvalues ​​to call the constructor, the move constructor can be called.

    #include <iostream>
    
    using namespace std;
    
    class x
    {
    public:
        x(int&& val)
        {
            cout << 123 << endl;
        }
        x() = default;
    };
    
    int main()
    {
        x(567);
    
        return 0;
    }
    

    In the above code, because I am passing an rvalue in, the constructor will be called. http://stackoverflow.com/ques... This discusses when to use the move constructor.
    Title title! ! ! A major discovery. I checked the information and then did my own experiments and found that x(x()) is a function declaration! If you declare another x(x()) below your x a, an error should be reported when compiling and running; the following is my test code, you can also try it, so your line does not call the move constructor!

    #include <iostream>
    #include <utility>
    
    using namespace std;
    
    class x
    {
    public:
        x(int&& val)
        {
            cout << "sdfs";
        }
        x()=default;
    };
    
    int func()
    {
        return 123;
    }
    class AA
    {
    public:
        AA(int&&){cout << "no" << endl;}
    };
    
    //x(func())
    //{
    //    cout << "function called" << endl;
    //}
    //AA(func());
    AA(funcall())
    {
        cout << "here\n";
    }
    
    //x(x());
    //AA(x());
    
    int main()
    {
        
        //(x)func();
        x(123);
        x(func());
        //AA(123);
        //funcall();
        return 0;
    }

    reply
    0
  • 阿神

    阿神2017-04-17 14:34:10

    #include <iostream>
    #include <utility>
    
    class X {
    public:
        X( X&& item) {
            std::cout << 123 << std::endl;
        }
    
        X() = default;
    };
    
    
    int main() {
        X(X()); // X(std::move(X())); 这个会输出 123
    }

    copy assignment operator should be written like this:

    class X {
        X operator=( const X &rhs ) {
            // ...
        }
    }

    reply
    0
  • 黄舟

    黄舟2017-04-17 14:34:10

    Try x{x{}}

    reply
    0
  • Cancelreply