Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/128.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 利用移动语义自动隐式生成CTOR_C++_C++11_Constructor_Default_Move Semantics - Fatal编程技术网

C++ 利用移动语义自动隐式生成CTOR

C++ 利用移动语义自动隐式生成CTOR,c++,c++11,constructor,default,move-semantics,C++,C++11,Constructor,Default,Move Semantics,让我们有一个有n个字段的类。每个字段都可以移动。那么我们必须显式定义2^n构造函数吗 n=2的示例: struct A{ std::vector<B> a; std::shared_ptr<B> b; A(std::vector<B> &a, std::shared_ptr<B> &b):a(a),b(b){}; A(std::vector<B> &a, std::shared_ptr<B>

让我们有一个有n个字段的类。每个字段都可以移动。那么我们必须显式定义2^n构造函数吗

n=2的示例:

struct A{
 std::vector<B> a;
 std::shared_ptr<B> b;
 A(std::vector<B> &a, std::shared_ptr<B> &b):a(a),b(b){};
 A(std::vector<B> &a, std::shared_ptr<B> &&b):a(a),b(std::move(b)){};
 A(std::vector<B> &&a, std::shared_ptr<B> &b):a(std::move(a)),b(b){};
 A(std::vector<B> &&a, std::shared_ptr<B> &&b):a(std::move(a)),b(std::move(b)){};
};
....
A aaa({{},{}}, shared_ptr<B>(new B()));
std::shared_ptr<B> b = ....;
A bbb({{},{}}, b);
结构A{ std::载体a; std::共享的ptr b; A(std::vector&A,std::shared_ptr&b):A(A),b(b){}; A(std::vector&A,std::shared_ptr&b):A(A),b(std::move(b)){}; A(std::vector&&A,std::shared_ptr&b):A(std::move(A)),b(b){}; A(std::vector&&A,std::shared_ptr&&b):A(std::move(A)),b(std::move(b)){; }; .... aaa({{},{}},shared_ptr(new B()); std::shared_ptr b=。。。。; A bbb({{},{}},b);
您对特殊成员函数的定义不正确,复制/移动构造函数不是根据类成员定义的,而是根据类定义的

而不是

class_name(const member_1&, ..., const member_n&)
class_name(const member_1&&, ..., const member_n&&)
您必须将复制/移动构造函数定义为:

class_name(const class_name&) // copy-constructor
class_name(class_name&&) // move constructor

在它内部,使用复制/移动语义。请参见

您可以通过拥有完美的转发模板构造函数来解决此问题:

struct A {
    std::vector<B> a;
    std::shared_ptr<B> b;
    template <typename AA, typename BB> A(AA&& a, BB&& b) :
        a(std::forward<AA>(a)), b(std::forward<BB>(b)) { }
};

我的意思不是复制类A的对象,而是在不复制的情况下使用右值构造类
标准::共享。。。。;A bbb({{},{}},b)为什么在原型中使用
AA&&a
?此函数是否也适用于左值引用?对于模板类型参数,&&&“有一个特殊的含义:它将使编译器将模板参数推断为与传递给函数的参数完全相同的类型(包括所有限定符)。我终于设法修复了回复更新中的所有键入错误:)请检查谢谢。关于参照系折叠也很有用。
void func1(int&&) { }
template <typename A> void func2(A&& t) {
    func3(t);
    func4(std::forward<A>(t);
}
template <typename B> void func3(B&&) { }
template <typename C> void func4(C&&) { }

int foo;
const int bar;

func1(foo); // ERROR
func1(bar); // ERROR
func1(std::move(foo)); // OK

func2(foo); // OK, A = int&, B = int&, C = int&
func2(bar); // OK, A = const int&, B = const int&, C = const int&
func2(std::move(foo)); // OK, A = int&&, B = int&, C = int&& <- note how && collapses to & without std::forward