Pointer indication is not deleted

I came across something that I can’t understand, so I think I'm missing something in the larger C ++ picture.

In short, my question is: how to save a mutable, non-removable, possibly NULL instance of an object in a class.

Longer version:

I have the following scenario: a bunch of classes (which I can change a bit, but not completely refactored), most of which I need to use an object. This object, while modified, is managed by someone else, so it cannot be deleted.

Some of the classes in the group do not need such an object - they reuse code from other classes, but through the available parameters provided to these classes, it is guaranteed that even if the object is provided, it will not be used.

The current implementation uses a pointer-to-const-object ( const Obj *). This, in turn, means that all methods of the object must be const and most fields are mutable. This is a messy solution, since the fields declared mutableare available for validation (so it’s exactly the opposite of the C ++ lite entry here ). It also partially solves the "do-not-delete-this-here" problem (the compiler does not complain, but constis an indication in front of the object).

If I used a reference to this object, I would force some callers to create a "dummy" object and provide it to the class that they create. It is also erratic, in addition to being a waste of resources. I cannot create a global object that may be behind the "NULL" link due to project constraints.

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

, , const-pointer-to-object (Obj * const) - , - - const - .

- ?

+3
6

, shared_ptr/weak_ptr. . .

/

boost::shared_ptr<T>

boost::weak_ptr<T>

ptr, :

void MyClass::Reassign(boost::weak_ptr<T> tPtr)
{
    m_tPtr = tPtr;
}

ptr, , :

void MyClass::Use()
{
    boost::shared_ptr<T> m_temporarySharedPtr = m_tPtr.lock();
    if (m_temporarySharedPtr)
    {
        //...
    }
}

ptr "NULL", shared_ptr

void MyClass::MakeNull()
{
    m_tPtr.reset();
}
+6

. attemp . -.

+6

, , :

template <typename T> class Wrapper
{
public:
    Wrapper(T *p=0) : pointer(p) {}

    T       *operator->()       {return pointer;}
    T const *operator->() const {return pointer;}
    operator bool()       const {return pointer;}

private:
    T *pointer;
};

, , delete . struct class (.. , -> ). , , , :

class User
{
public:
    void Assign(Object *o) {object = o;}
    void UseObject() {if (object) object->Use();}

private:
    Wrapper<Object> object;
};

, :

delete wrapper.operator->();
+1

shared_ptr.

0

( ) , , .

, , . *, .

0

- ?...

Obj , Obj* cont pObj, ( 0, ), pObj ?

if ( pObj ){ pObj->foo(); }

foo , .

/ Obj.

0

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


All Articles