简体   繁体   English

将右值引用传递给 class 构造函数有什么意义?

[英]What is point of passing rvalue reference to class constructor?

Ok好的

So I have a class, MyClass.所以我有一个 class,MyClass。 I would like to construct this class with say a vector of ints.我想用整数向量构造这个 class 。 I want to move this vector into the object.我想将此向量移动到 object 中。 The class is not templated. class 没有模板化。

class Myclass {
     public:
     Myclass (std::vector<int> && in) : vec{in} {};
     Myclass (std::vector<int> & in) : vec{in} {};

    private:
    std::vector<int> vec;
    }

In my main I have在我的主要我有

std::vector<int> orig (100);
Myclass A {orig};
std::cout << A.size() << '\n';

I want "orig" to be empty after moving it into "A".我希望将“orig”移入“A”后为空。 That does not happen in either of the options above.上述任何一个选项都不会发生这种情况。 Even if I do即使我这样做

    std::vector<int> orig (100);
    Myclass A {std::move(orig)};
    std::cout << A.size() << '\n';  // still prints 100

It looks like I can achieve it via看起来我可以通过

 Myclass (std::vector<int> && in) : vec{std::move(in)} {};   // (1)

OR或者

 Myclass (std::vector<int> & in) : vec{std::move(in)} {};    // (2)

OR或者

Myclass (std::vector<int> && in) : vec{std::forward<std::vector<int>(in)} {};    // (3)

My question is why does (1) appear to behave exactly like (2)?我的问题是为什么 (1) 的行为与 (2) 完全一样?

The thing to remember about references, rvalue and lvalue, is that they are lvalues.关于引用,右值和左值要记住的是它们是左值。 That means if you have a reference to a thing, that reference is an lvalue and you need std::move to cast it to an rvalue so it can be moved.这意味着如果你有一个东西的引用,那个引用是一个左值,你需要std::move将它转换为一个右值,以便它可以移动。

The real difference between Myclass (std::vector<int> && in) and Myclass (std::vector<int> & in) is that with the first you have to use Myclass (std::vector<int> && in)Myclass (std::vector<int> & in)之间的真正区别在于你必须使用第一个

Myclass A {std::move(orig)};
// or
Myclass A {std::vector(100)};

and cant pass an lvalue to it, where as with second you can only uses并且不能将左值传递给它,而与 second 一样,您只能使用

Myclass A {orig};

as it wont let you pass an rvalue to it.因为它不会让您将右值传递给它。


Also note that constructor 3 is "incorrect".另请注意,构造函数 3 是“不正确的”。 You should only use std::forward when you have a forwarding reference.只有在有转发引用时才应使用std::forward std::vector<int> && in is a rvalue reference, not a forwarding one so you should use std::move instead. std::vector<int> && in是右值引用,而不是转发引用,因此您应该改用std::move To use forward correctly you'd need a template constructor like要正确使用 forward,您需要一个模板构造函数,例如

template <typename T, std::enable_if_t<
                                       std::is_same<std::decay_t<T>, 
                                       std::vector<int>>, bool> = true>
Myclass (T&& in) : vec{std::forward<T>(in)} {}; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM