加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

带有右值引用的C构造函数

发布时间:2020-12-16 10:21:58 所属栏目:百科 来源:网络整理
导读:考虑这个有三个构造函数的类: class Circle {public: Circle(int r) { _radius = r; }Circle(const Circle c){ _radius = c.radius(); cout endl "Copy constructor with lvalue reference. Radius: " _radius;}Circle(Circle c){ _radius = c.radius(); co
考虑这个有三个构造函数的类:

class Circle {

public:
 Circle(int r) {
      _radius = r;
 }

Circle(const Circle& c){
    _radius = c.radius();
    cout << endl << "Copy constructor with lvalue reference. Radius: " << _radius;
}

Circle(Circle&& c){
    _radius = c.radius();
    cout << endl << "Copy constructor with rvalue reference. Radius:" << _radius;
}

int radius() const {
    return _radius;
}

private:
    int _radius;
};

int main() {
     Circle c1(2);
     Circle c2(c1);
     cout << endl << c2.radius(); 
     Circle c3(Circle(4));
     cout << endl << c3.radius(); 
     return 0;
 }

用“g -std = c 0x”编译.输出是:

Copy constructor with lvalue reference. Radius: 2
2
4

好.调用前两种情况的正确构造函数.但对于
第三种情况,即Circle c3(Circle(4)),我期待第三种构造函数,
(要用rvalue referecne复制构造函数)要调用,但事实并非如此.
显然有一些构造函数被调用,因为c3被正确实例化了但是我
不明白为什么编译器没有使用显式提供的
一.我在这里错过了什么吗?

解决方法

为了获取rvalue引用,它应该是非const的,因为构造函数参数的内容将被移动,并且通常这是一个更改操作数状态的操作(尽管不是在您的特定情况下):

Circle(Circle&& c){ }

此外,您在这里看到了一个副本省略:

Circle c3(Circle(4));

所以不会调用move构造函数.这是可能会或可能不会发生的标准编译器优化.如果你要像这样构建一个Circle:

Circle c3(std::move(c1));

然后你会调用移动构造函数.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读