Is there a way to initialize a class with a constructed class without using std :: move?

// Example program
#include <iostream>
#include <string>
#include <utility>

class A {
public:
    int x; 
};

class B {
public:
    B(A &&a) : m_a(std::move(a)) {}
    A m_a;
};

int main()
{
    B var(std::move(A()));
    // B var(A()); // does not compile why?

    std::cout << var.m_a.x << "\n";

}

In the above snippet, the commented line is not compiled. An error message appears that treats var as a function declaration. Even if A has a parameter for the constructor, it is still treated as a function declaration. Is there a way to write it so that it is not treated as a function declaration? Using typename in this case does not help.

+4
source share
3 answers

, , , . , - X, Y.

list:

B var{A()}; // note the use of brackets

, , . A :

B var(A{});
B var{A{}};

, ? , , , :

int foo(int (*bar)());

, int. - :

int foo(int bar());

, . (parameter-declaration-clause), type-id, abstract-declarator. :

int foo(int());

- .

, :

B var(A());

- B, A(). . , , !

, var .

var , . - [dcl.ambig.res]/1:

[...] , .

. :

int foo(int());

, : foo , . , B var(A()) , .

[dcl.ambig.res]/1, # 1, , [dcl.ambig.res]/1, note # 1:

[. . , . - ]

[:

struct S {
  S(int);
};

void foo(double a) {
 S w(int(a));                  // function declaration
 S x(int());                   // function declaration
 S y((int(a)));                // object declaration
 S y((int)a);                  // object declaration
 S z = int(a);                 // object declaration
}

- ]

+9

A

B var(A{});

.

+2
B var = A();

B(A&&) explicit ( , ).

B var(A{});

.

The compiler believes that your original line is a function declaration, because in C ++ you can declare everything locally, even functions or structures:

int f()
{
   void f(); // You declare that function exists.
   class C; // You declare a class called `C` exists.
}

In your case:

B var(A());

The compiler sees that there is a function with a name varthat returns Band receives a function that takes no parameters and returns A.

You must eliminate this using either of the two approaches presented above.

+2
source

Source: https://habr.com/ru/post/1664633/


All Articles