Constructor Access Rules

if I compile (under g ++) and run the following code, it prints "Foo :: Foo (int)". However, after private instance constructors and assignment operators are closed, it cannot compile with the following error: "error:" Foo :: Foo (const Foo &) is private. "How does it need a copy constructor if it calls the standard constructor at runtime?

#include <iostream>

using namespace std;

struct Foo {
    Foo(int x) {
        cout << __PRETTY_FUNCTION__ << endl;
    }


    Foo(const Foo& f) {
        cout << __PRETTY_FUNCTION__ << endl;
    }

    Foo& operator=(const Foo& f) {
        cout << __PRETTY_FUNCTION__ << endl;
        return *this;
    }
};

int main() {
    Foo f = Foo(3);
}
+3
source share
2 answers

The copy constructor is used here:

Foo f = Foo(3);

This is equivalent to:

Foo f( Foo(3) );

where the first set of parens re calls the copy constructor call. You can avoid this by saying:

Foo f(3);

, , ( ). ++ (. 12.8/15), .

+15

, , , . (, IO ).

, , , .

Foo f = Foo(3);

.

Foo f(3);

. , , .

12.8.15

, , / . , , .111). ( ):

- return class return type, cv- ,

- , (12.2) cv- ,

. " ".

+2

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


All Articles