具有右值引用的C ++构造函数 [英] C++ constructor with rvalue reference

查看:84
本文介绍了具有右值引用的C ++构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用三个构造函数来考虑此类:

Consider this class with three constructors:

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。输出为:

Compiled with "g++ -std=c++0x". The output is:

Copy constructor with lvalue reference. Radius: 2
2
4

确定。调用前两种情况的正确构造函数。但是对于
的第三种情况,即Circle c3(Circle(4)),我希望调用第三种构造函数,即
(带有右值引用的复制构造函数),但事实并非如此。
显然,由于正确地实例化了c3,因此调用了一些构造函数,但是我
不明白为什么编译器未使用显式提供的
。我在这里丢失了什么吗?

OK. The right constructors for the first two cases are called. But for the third case i.e., Circle c3(Circle(4)), I'd expect the third constructor, (copy constructor with rvalue referecne) to be called but it's not the case. Obviously some constructor is called since c3 is properly instantiated but I don't understand why the compiler is not using the explicitly provided one. Am I missing something here?

推荐答案

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

In order to take the rvalue reference, it should be non-const, since the contents of the constructor argument will be moved and typically this is an operation that changes the state of the operand (although not in your particular case):

Circle(Circle&& c){ }

此外,您还在此处看到了复制省略项:

Also, you are seeing a copy elision here:

Circle c3(Circle(4));

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

so the move constructor doesn't get invoked. This is a standard compiler optimization that may or may not happen. If you were to construct a Circle like this:

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

然后您将调用move构造函数。

then you would invoke the move constructor.

这篇关于具有右值引用的C ++构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆