rreference作为参数调用移动构造函数吗?

问题描述 投票:0回答:1

我现在正在学习 C++ 移动语义,但我对代码打击遇到了麻烦:

#include <iostream>
class A {
    public:
        A() { std::cout << "Default Constructor\n"; }
        A(const A& other) { std::cout << "Copy Constructor\n"; }
        A(A&& other) noexcept { std::cout << "Move Constructor\n"; }
    
        // 仅仅是为了避免编译器优化而定义
        A& operator=(const A& other) {
            std::cout << "Copy Assignment Operator\n";
            return *this;
        }
        A& operator=(A&& other) noexcept {
            std::cout << "Move Assignment Operator\n";
            return *this;
        }
    };
    
    void func(A&& a) {
        // Do something with 'a'
    }
    
    int main() {
        A a;  // 调用默认构造函数
        func(std::move(a));  // 调用移动构造函数
        func(A());  // 直接传递右值,调用移动构造函数
        return 0;
    }

但是输出是

Default Constructor
Default Constructor

我想知道为什么移动构造函数不被调用?并且只调用了两个默认构造函数?编译器是“g++ 13.2” enter image description here

c++
1个回答
0
投票
void func(A&& a) { }

int main() {
        A a;  // default constructor
        func(std::move(a));  // you are merely creating a reference that allows moving.
                             // Your func doesn't do anything with it, so no object is created/moved.
        func(A());  // again, you create an object (default constructor), then pass it
                   // to func() as a reference that would allow moving.
        return 0;
    }
© www.soinside.com 2019 - 2024. All rights reserved.