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

C++ 构造函数const & -fno-elide-constructors,第1张

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

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5098397.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-17
下一篇 2022-11-16

发表评论

登录后才能评论

评论列表(0条)

保存