【问题标题】:How to get the move constructor calling deliberately [duplicate]如何故意调用移动构造函数[重复]
【发布时间】:2015-08-31 09:10:20
【问题描述】:

考虑以下代码:

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

【问题讨论】:

  • 在其他人给出好的答案之前,请查看en.cppreference.com/w/cpp/utility/move
  • 调用移动构造函数被简单地优化掉了。 “复制省略”是你的朋友!
  • 看起来 getBase() 正在被内联 - 尝试在其自己的翻译单元中构建它,然后进行链接。
  • @TobySpeight 这是一个分段错误!
  • @Klaus 这是我的观点;我怎样才能强制调用移动构造函数? std::move() 是一种方法。

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


【解决方案1】:

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

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

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

【讨论】:

  • getBase() 已经是纯右值,您可以防止复制省略发生
  • @Ormei,而不是指 cmets,也许您可​​以直接在答案中解释这一点?
  • @PiotrSkotnicki 如果getBase() 已经是prvalue,那么为什么不调用移动构造函数?
  • 当您编写Base b4 = getBase(); 时,复制省略会优化代码以在b4 的位置构造Base 对象,因此根本不会调用复制或移动构造函数。
  • @Ormei 你能建议任何其他方式来故意调用移动构造函数吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-22
  • 1970-01-01
  • 1970-01-01
  • 2021-12-12
  • 2022-11-21
  • 1970-01-01
  • 2019-06-10
相关资源
最近更新 更多