C ++ reference can be assignable?

I messed around with the links enclosed in container classes. Why is the following code legal and seems to behave correctly?

#include <iostream>

class Foo
{
public:
  Foo( int i ) : i_( i ) {}
  int i_;
};

class FooWrapper
{
public:
  FooWrapper( Foo& foo ) : foo_( foo ) {}
  Foo& foo_;
};

int main( int argc, char* argv[] )
{
  Foo foo( 42 );
  FooWrapper fw( foo );
  FooWrapper fw2 = fw;
  std::cout << fw2.foo_.i_ << std::endl;
  return 0;
}

In the absence of an explicit expression operator=, I believe that C ++ performs a phased copy. Therefore, when I do FooWrapper fw2 = fw;, these are not two operations: (1) create FooWrapper fwwith the default ctor, followed by (2) the assignment from fwto fw2? I am sure that this does not happen because the link cannot be created uninitialized, since the creation is fw2actually considered as building a copy?

Sometimes I don’t understand the role of copying and assigning; they seem to bleed into each other sometimes, as in this example, but there is probably a rule that I don’t know about. I would appreciate an explanation.

+4
3

fw2, fw. -.

FooWrapper fw2 = fw;

() , , , ( ++ 11).

#include <iostream>

struct foo
{
    foo() {std::cout << "Default constructor" << '\n';}
    foo(foo const&) {std::cout << "Copy constructor" << '\n';}
    foo& operator=(foo const&) {std::cout << "Copy assignment operator" << '\n'; return *this; }
    foo& operator=(foo &&) {std::cout << "Move assignment operator" << '\n'; return *this; }
};

int main( int argc, char* argv[] )
{
    foo a;            // Default constructor
    foo b = a;        // Copy constructor
    foo c;            // Default constructor
    c = b;            // Copy assignment operator
    b = std::move(c); // Move assignment operator
}
+3

= , FooWrapper fw2 = fw; fw2 ( ). .

: no, . , FooWrapper, :

FooWrapper fw2;
fw2 = fw;

... . "". , , , / .

+4

. FooWrapper fw2 = fw; FooWrapper fw2(fw);

: http://en.cppreference.com/w/cpp/language/copy_constructor

+3

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


All Articles