栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++ 构造函数const & -fno-elide-constructors

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++ 构造函数const & -fno-elide-constructors

why const

https://www.geeksforgeeks.org/copy-constructor-argument-const/

最开始是想查一下为什么要用const

#include
using namespace std;

class Test
{

public:
Test(Test &t) { }
Test()	 {  }
};

Test fun()
{
	cout << "fun() Calledn";
	Test t;
	return t;
}

int main()
{
	Test t1;
	Test t2 = fun();
	return 0;
}



下面也说了相关的问题

https://stackoverflow.com/questions/16956693/why-c-copy-constructor-must-use-const-object

You couldn’t create copies from temporary reference, because temporary objects are rvalue, and can’t be bound to reference to non-const.

下面说的是rvalue的问题
https://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/

这里面讲到了临时的值如果给了const 就会一直存续,我翻译的不太明白,可以自行看原文或者查一下相关的知识。我自己想了一下,应该是加了const 会存储在全局区,之前是在stack,用完就释放了(这里很可能不太对,希望有人给指点一下)
(关于分区的问题我看不同教材上的分类也有稍许区别)

这里讲的如何析构

我自己写了个测试一下


#include
using namespace std;
  
class Test
{
    
public:
   Test( const Test &t) { 
        cout << "1" << endl;
       }
   Test()        { 
       cout << "3" << endl; }
    Test &operator=(const Test &){
        cout << "operator" << endl;
        return *this;
    }
};
  
Test fun()
{
    cout << "fun() Calledn";
    Test t;
    cout << "00" << endl;
    return t;
}
  
int main()
{
    //Test t1;
    //cout << "2" << endl;
    //Test t2 =  fun();
    //Test t3(t2);
    const Test & t10 = Test(); //如果去掉const 就会报错
    Test & t10 = Test(); //这样写就会报错 
    //error: cannot bind non-const lvalue reference of type 
    //Test&’ to an rvalue of type ‘Test’
  	//40 |     Test & t10 = Test();
    
    //Test t10 = Test(); // 先有普通构造,后有拷贝构造的,需要两个构造函数 但编译器现在都给省略了,所以说就可以默认为只有一次构造就行了
    return 0;
}          

最后会输出3

why &

这个写的就很好啦
https://blog.csdn.net/XiyouLinux_Kangyijie/article/details/78939291

-fno-elide-constructors
The C++ standard allows an implementation to omit creating a
temporary which is only used to initialize another object of the
same type. Specifying this option disables that optimization, and
forces G++ to call the copy constructor in all cases.

https://stackoverflow.com/questions/27086573/when-and-why-would-i-use-fno-elide-constructors

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/429635.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号