Is using C ++ pointers always bad?

I was told not to use pointers in C ++. It seems that I cannot avoid them, however, in the code I'm trying to write, or maybe I am missing out on other great C ++ features.

I want to create a class (class1) that contains another class (class2) as a data member. Then I want class2 to know about class1 and be able to communicate with it.

I could refer to class1 as a member in class2, but that means I need to provide a reference to class1 as a parameter in the constructor of class2 and use initializer lists that I don't want. I am trying to do this without requiring a constructor to do this.

I would like class2 to have a member function called Initialise that could take a reference to class1, but this seems impossible without using pointers. What would people recommend here? Thanks in advance.

The code is completely simplified to get the basic idea:

class class1
{
    public:
        InitialiseClass2()
        {
            c2.Initialise(this);
        }

    private:
        class2 c2;

};

class class2
{
    public:
        Initialise(class1* c1)
        {
            this->c1 = c1;
        }

    private:
        class1* c1;

};
+4
source share
5 answers

this seems impossible without using pointers

This is not true. Indeed, to process a link to some other object, take the link into the constructor:

class class2
{
    public:
        class2(class1& c1)
           : c1(c1)
        {}

    private:
        class1& c1;
};

- , . , , Initialise RAII (, !). , , ; , smart-pointer — a std::weak_ptr.

, .

"" ? , , . , "" , .

? .

, , , - .

+5

, ++ , - . - , .

, . - . ++ . , .

+4

nullptr, - ( - ).

.

std::shared_ptr std::unique_ptr .

+2

, 2 , , ? - , 2 , , , ). :

  • 1 ( )
  • Observer ( 3- , , , , 2 , ).
  • () ,
  • ( , ++ 11) ,
  • .
  • , , , .
  • , (, )

, - . ;)

. , , ( , , , , , , ). "" , , , .

0

, , , , . , .

++. , , , , , , , ++.

- . ++ ( ), , . ++ , , . , . , .

, , raw , . , , , , / , .

( ) , , . , , ( /= ), . - , , ( ).

0

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


All Articles