Modern C++ API: Don’t Declare Entities As Pointers

Entities, such as the DomainParticipant or the DataReader should never be created as pointers (i.e. using new). They already implement reference semantics and behave like a shared_ptrA DomainParticipant (or any other reference type in the API) is a wrapper of shared_ptr<DomainParticipantImpl>.

Whenever you declare an Entity, as a class member, a local variable, etc., declare it as a regular variable, for example:

class MyClass {
    ... 
 
    // Correct declaration:
    DomainParticipant my_participant; 
 
    // Don’t do this:
    //   DomainParticipant * my_participant;  
    // nor this:
    //   shared_ptr<DomainParticipant> my_participant;
 };

This may force you to call a DomainParticipant constructor in the constructors of MyClass, for example:

class MyClass {
public:
    MyClass(int domain_id) : my_participant(domain_id)
    {
    }

private:
    DomainParticipant my_participant; 
};

But if for some reason you can’t create the object right there, you can use the constructor that receives dds::core::null (or nullptr in C++11) and create the actual DomainParticipant later:

class MyClass {
public:
    MyClass() : my_participant(nullptr)
    {
    } 
 
    int create_participant(int domain_id)
    {
       // Creates the DomainParticipant and assigns the reference
       // to my_participant. After this assignment, this DomainParticipant's
       // reference count is 1.
       my_participant = DomainParticipant(domain_id);
    }

private:
    DomainParticipant my_participant;
};

Note that the DomainParticipant will be automatically deleted by MyClass's implicit destructor, since we are not holding any other references to it other than my_participant.