c++ - 如何让移动构造函数有意调用

标签 c++ c++11 move-constructor

<分区>

考虑以下代码:

class Base {
public:
    int bi;
    Base() : bi(100)    {std::cout << "\nBase default constructor ...";}
    Base(int i) : bi(i) {std::cout << "\nBase int constructor: "<< bi;}
    Base(const Base& b) {std::cout << "\nBase copy constructor";}
    Base(Base&& b)      {std::cout << "\nBase move constructor";}
};

Base getBase() {
    cout << "\nIn getBase()";
    return Base();  
}
int main() {
    Base b2(getBase());  
    Base b3 = Base(2);   
    Base b4 = getBase(); 
}

尽管给出了右值,但 main 中的上述构造都没有调用移动构造函数。有没有办法确保调用用户定义的移动构造函数?

这是我得到的:

In getBase()    
Base default constructor ...
Base int constructor: 2
In getBase()
Base default constructor ...
Base destructor: 100
Base destructor: 2
Base destructor: 100

最佳答案

您可以使用 std::move() 方法:

Base b4 = std::move(getBase());

这确保了移动构造函数被调用,但在这一行中它阻止了复制省略以优化复制构造函数。无需调用任何构造函数,因此这是如何不使用 std::move() 的更多示例。

关于c++ - 如何让移动构造函数有意调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32307671/

相关文章:

c++ - std::vector 不使用具有 noexcept move 构造的对象调用 move 构造函数

c++ - 继承后重新获得 move 可构造性

c++ - 每帧多次调用 glBufferSubData

c++ - tcpdump 没有为我的 C++ 应用程序显示任何内容?

c++ - 生成文件语法错误。缺少分隔符

c++ - 模板类特化与函数重载

c++ - nullptr 初始值和 WinAPI NULL 返回

c++ - 通过 decltype 声明一个 vector

c++ - 如何防止右值和左值成员函数之间的代码重复?

c++ - %p说明符仅用于有效的指针吗?