How to create a permalink to an object?

I have a project that includes 3 classes as my data structures. We call classes A, Band C.

I need to create objects A, Band Cwhile parsing my input. Each class object Cneeds to track the corresponding objects in Aand classes B. My current implementation is as follows:

class C {
    private:
        A* a;
        B* b;
    public:
        void setA(A* a);
        void setB(B* b);
}

I assign Aand Bwhen I create objects Aand Bwith the help of the operator new. The problem is that I do not want the class object to Cbe able to modify Aand B. In fact, I only need to know what Aand Bmatch specific C.

One solution could be to define Aand Bhow constpointers / references to objects. However, in the case of object references, I need to define them as soon as I declare them. The problem is that I am parsing multiple files, and I cannot assign the correct links to Aand Bwhen I define them. In other words, Aboth Bare created at different times in my program and may not be available when I create C.

I read lately that it is better to avoid raw pointers as much as possible, and so I am trying to implement this using object references instead of pointers. In fact, this makes it difficult to determine which one should be used at different stages of my program.

My questions are as follows:

1) ?

2) , , A B, ?

3) unique_ptr A B, ?

+4
2
  • ++, raw-. 4 ++ Scott Meyers. , . Effective ++, More Effective ++ Effective STL.

  • , , . .

    , const ( ), const. const * const type &, const .

    , const. , const, , . , ? const * nullptr , . , , , , b. , nullptr, , , .

  • , std:: unique_ptr < > . / . nullptr . , , . const type &, , .

, , , . , std:: unique_ptr < > - , .

:

class C {
    private:
        const A* a;
        const B* b;
    public:
        void setA(const A* a);
        void setB(const B* b);
}
+2

, , C a b. , , a b c.

const:

A const* a;
A const* b;

, .

, C A B, . ,

(1) ; , , . :

function(a); // Not sure if it is a reference
function(&a); // You know it is that actual object

(2) const, ""

0

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


All Articles