gpt4 book ai didi

c++ - 你怎么称呼带有右值引用参数的构造函数?

转载 作者:行者123 更新时间:2023-11-28 00:06:36 24 4
gpt4 key购买 nike

A move constructor of class T is a non-template constructor whose first parameter is T&&, const T&&, volatile T&&, or const volatile T&&, and either there are no other parameters, or the rest of the parameters all have default values.

如果一个构造函数接受了一个不同类型的右值引用,你会怎么调用它:

#include <string>
#include <vector>

struct Bar
{
std::string bs;
std::vector<char> bv;

};

struct Foo {
std::string fs;
std::vector<char> fv;

Foo(Bar && b)
: fs(std::move(b.bs))
, fv(std::move(b.bv))
{}
};

最佳答案

你称之为“构造函数”。

所有类型的函数都可以接受类型的右值引用,就像它们可以接受左值引用、值等一样。只有当编译器/语言需要特殊对待它们时,它们才会获得特殊名称。并且编译器不会将此构造函数与任何其他采用右值的函数区别对待。

虽然一般来说,这种构造函数的含义是它从给定的Bar 移动。事实上,您永远不应该采用您不移动(或转发)的右值引用参数。无论是将 Bar 移动到自身,还是作为创建 Foo 的内部数据的辅助操作,或者其他任何取决于构造函数实现的操作。

关于c++ - 你怎么称呼带有右值引用参数的构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35364975/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com