据我所知,如果函数按值返回,则将其视为右值。
但是当我想传递函数返回值以将构造函数作为参数移动时,不会调用移动构造函数而是复制构造函数。
这是我的代码:
#include <stdio.h>
#include <string.h> // strncmp
#include <vector>
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
class apple_t {
public:
apple_t( double data2 ) {
data = &data2;
cout<<"value constructor"<<endl;
}
apple_t( const apple_t& apple ) {
data = apple.data;
cout<<"copy constructor"<<endl;
}
apple_t( apple_t&& apple ) {
data = apple.data;
apple.data = nullptr;
cout<<"move constructor"<<endl;
}
~apple_t(){ cout<<"apple killed"<<endl;}
public:
double* data;
};
apple_t create_apple(){ apple_t apple(apple_t(40.7)); return apple; }
int main(int argc, char** argv)
{
apple_t apple1(20.5);
apple_t apple2(apple1);
apple_t apple3(move(apple1));// std::move produces an rvalue-reference
apple_t apple4( create_apple() );
}
输出如下:
value constructor
copy constructor
move constructor
value constructor
apple killed
apple killed
apple killed
apple killed
我期待&#34; apple_t apple4(create_apple());&#34;,应调用移动构造函数而不是普通构造函数&#34; apple_t(double data2)&#34;。
有人可以帮帮我吗?