C++11 右值引用 编译器验证

1. 简介

右值引用 这个概念是C++11提出的,具体概念参考wikipedia
本文主要是写一个简单的demo程序,然后使用编译器特定选项,验证右值引用。

2. 代码示例:

#include <iostream>
using namespace std;

class A { 
public:
        int *p; 
        A()             { cout << "   constructor: " << __FUNCTION__ << endl; }
        A(const A& rhs) { cout << "   copy constructor: " << __FUNCTION__ << endl; }

        A(A&& rhs)      { cout << "   right value copy constructor: " <<  __FUNCTION__ << endl; }
        ~A()            { cout << "   destructor: " << __FUNCTION__ << endl; }
};

A getA() {
        A a;
        a.p = 0;
        return a;
}

int main() {
        // A x(std::move(getA()));
        cout << "BEGIN: " << __LINE__ << endl;
        A x = getA();
        cout << "END: " << __LINE__ << endl;
        return 0;
}

代码有三个构造函数,分别是:
(1)默认构造函数;
(2)左值拷贝构造函数;
(3)右值拷贝构造函数。

上述代码除了 【右值拷贝构造函数】 外,与98/03 C++没有区别。
关键点在于 【右值拷贝构造函数】何时被调用?

3.编译、执行

编译环境:

# uname -a
Linux localhost.localdomain 3.16.4-200.fc20.i686+PAE #1 SMP Mon Oct 6 13:08:54 UTC 2014 i686 i686 i386 GNU/Linux

3.1 g++编译

编译命令如下:

# gcc --version
gcc (GCC) 4.8.3 20140911 (Red Hat 4.8.3-7)
Copyright (C) 2013 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

# g++ -std=c++11 -fno-elide-constructors -pedantic a.cpp

执行:

./a.out

输出:

BEGIN: 22
   constructor: A
   right value copy constructor: A
   destructor: ~A
   right value copy constructor: A
   destructor: ~A
END: 24
   destructor: ~A

3.2 clang++编译

编译命令如下:

# clang --version
clang version 3.4.2 (tags/RELEASE_34/dot2-final)
Target: i386-redhat-linux-gnu
Thread model: posix

#clang++ -std=c++11 -fno-elide-constructors -pedantic a.cpp

执行:

./a.out 
BEGIN: 22
   constructor: A
   destructor: ~A
   right value copy constructor: A
   destructor: ~A
END: 24
   destructor: ~A

4. 结果分析

我们使用了-fno-elide-constructors -pedantic编译选项,关闭了编译器优化(-fno-elide-constructors该选项就足够了)。

4.1 gcc输出分析:

(1)在函数getA()返回前需要将 对象a 拷贝出来,此处调用了 右值引用拷贝构造函数;
(2)在main函数中,初始化 对象x,再次调用 右值引用拷贝构造函数。

说明:
有一点我也不是很明白,为什么getA()调用的是 右值引用拷贝构造函数?毕竟 对象a 是左值。
解释:
a是 局部对象,函数执行完后该对象即将被析构。编译器考虑到此原因,直接使用 右值引用拷贝构造函数, 效率更高。
这种优化很简单,当然只是我的个人猜测

4.2 clang输出分析:

clang的输出结果很让我出乎意料,在getA()函数返回时,它没有调用任何拷贝构造函数。但是在 对象x 的初始化时,它调用了 右值引用拷贝构造函数。

疑问:
getA()函数已经返回,对象a 已经被析构了,你的右值引用拷贝构造函数从哪里拷贝内容呢(对象a已经被析构了)?
解释:
不知道怎么解释。
猜测:
肯定对 对象a 执行了拷贝操作,但是执行的具体方式我们不知道。也有可能和clang编译器版本有关系。因为电脑比较老,没有装更多的clang版本,小伙伴们自己可以多测试几个。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值