关于在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
- 关于在g++编译C++过程中调用移动构造函数
- Effective C++:条款09:绝不在构造和析构过程中调用virtual函数
- 《Effect C++》学习------条款09:绝不在构造和析构过程中调用virtual函数
- 读书笔记《Effective C++》条款09:绝不在构造和析构过程中调用virtual函数
- <Effective C++> Item 9:绝不在构造和析构过程中调用虚函数
- 在构造函数中调用构造函数
- 在构造函数中调用构造函数
- 关于c语言在函数调用过程中栈布局动态变化的讨论
- 关于c语言在函数调用过程中栈布局动态变化的讨论
- Effective C++——》条款9:绝不在构造和析构过程中调用virtual函数
- [初学遇坑]C++中简单的拷贝构造函数在g++/clang下不被调用
- c++:在类的构造函数中调用另一个构造函数
- C++:构造函数中调用虚函数
- C++:构造函数中调用虚函数
- C/C++—— 在构造函数中调用虚函数能实现多态吗(Vptr指针初始化的过程分析)
- 在成员函数中调用构造函数
- 在构造函数中调用虚函数
- 在构造函数中调用虚函数
- c# 银行管理
- Java泛型(二)——使用Gson解析复杂的泛型嵌套泛型数据结构
- 斯坦福大学卷积神经网络----Module 1 Lesson 1 图像分类
- Advice to professor Xin
- 如果有人问你 SQL 注入的资料,请叫他看这份速查表
- 关于在g++编译C++过程中调用移动构造函数
- nodejs的第二个小程序
- 图像是怎么转换为JPEG图像的
- 传统产业、传统企业为什么要进行互联网转型?
- HDU3450-Counting Sequences
- 排序算法总结(C++)
- poi导出excel例子
- ListView列表
- 打造CommonAdapter