关于在g++编译C++过程中调用移动构造函数

来源:互联网 发布:杠杆炒股盈利算法 编辑:程序博客网 时间:2024/06/06 15:50

最近在学习C++,写了段程序,g++下一直不能调用移动构造函数,换到VS2013下就没有问题,原来是需要使用g++编译的时候使用 -fno-elide-constructors 选项,而且开启c++11标准,完整命令如下:

g++ -o demo -std=c++11 -fno-elide-constructors demo.cpp


demo.cpp如下:

#include<iostream>#include<utility>#include<string>using namespace std;class myClass{  string *m_ps;public:  myClass()=default;  myClass(string *ps): m_ps(ps){cout<<"now is in the basic constructor!"<<endl;}  myClass(const myClass &p);  myClass(  myClass &&p) noexcept;  ~myClass(){    cout<<"now is in the ~myClass"<<endl;    delete m_ps;}  void print(void) const;};void myClass::print(void) const{  cout<<*m_ps<<endl;}myClass::myClass(const myClass &p){  cout<<"now is in the myClass(myClass &p)"<<endl;  string *temp = new string(*p.m_ps);  m_ps = temp;}myClass::myClass( myClass &&p) noexcept{  cout<<"now is in the myClass(myClass &&p)"<<endl;  m_ps = std::move(p.m_ps);  p.m_ps=nullptr;}int main(){  string *s =new string("hello world!");  cout<<"a: we wang to test basic constructor by string *"<<endl;  myClass a(s);  cout<<"b: we want to test copy constructor"<<endl;  myClass b(a);  cout<<"c: we want to test move constructor"<<endl;  myClass c(myClass(new string("haha"));//VS2013中如果这样用就会直接调用myClass(string *ps)这个函数了,估计被优化了,但是g++不会,VS2013中可以写个函数,函数内生成一个myClass对象返回,从而就会调用移动构造函数  c.print();  return 0;}


运行结果如下:


a: we wang to test basic constructor by string *now is in the basic constructor!b: we want to test copy constructornow is in the myClass(myClass &p)c: we want to test move constructornow is in the basic constructor!now is in the myClass(myClass &&p)now is in the ~myClasshahanow is in the ~myClassnow is in the ~myClassnow is in the ~myClass



0 0
原创粉丝点击