mardi 28 avril 2020

std::shared_ptr which is empty but not null

http://www.cplusplus.com/reference/memory/shared_ptr/ says

A shared_ptr that does not own any pointer is called an empty shared_ptr. A shared_ptr that points to no object is called a null shared_ptr and shall not be dereferenced. Notice though that an empty shared_ptr is not necessarily a null shared_ptr, and a null shared_ptr is not necessarily an empty shared_ptr.

Am I able to create an empty std::shared_ptr, i.e. one which does not own anything but which is not null, i.e. contains payload?

The usecase is to marry "legacy" code with the modern pointers: Given that foo's call syntax is not to be changed,

void foo(const MyClass* p) {
   if (p == nullptr) {
       auto defaultObject = std::make_shared<MyClass>("some", "parameters");
       defaultObject->doSomething();
       ...
       defaultObject->doSomethingElse();
       // The default object must be destroyed again
   } else {
       p->doSomething();
       ...
       p->doSomethingElse();
       // p must not be destroyed, its memory is managed somewhere else
   }
}

is there an implementation for doNotOwnButStillPointTo() which allows this:

void foo(const MyClass* p) {
    std::shared_ptr<MyClass> wrapper;
    if (p == nullptr) {
        // Create a default object
        wrapper = std::make_shared<MyClass>("some", "parameters");
    } else {
        wrapper = doNotOwnButStillPointTo(p);
    }

    wrapper->doSomething();
    ...
    wrapper->doSomethingElse();
    // p mus not be destroyed, the default object (if created) shall be
}

Or, to not fall for the XY-Problem, is there a different smart pointer available or none at all?

  • However, I want to add, that the line std::make_shared<MyClass>("some", "parameters") is actually a call to a more complex function which creates a shared_ptr. I'd like to retain this function and use its result

Aucun commentaire:

Enregistrer un commentaire