user18031247
user18031247

Reputation:

Is it OK to pass an unreferenced object as a parameter into a function?

Here is a super quick example of what I am thinking.

// Example program
#include <iostream>
#include <string>

class Obj
{
private:
    int myInt;
public:
    Obj()
    {
        myInt = 0;
    }
    ~Obj()
    {}
    
    void increment()
    { 
        myInt++; 
    }
    int getInt() 
    { 
        return myInt; 
    }
};

class A
{
public:
    Obj* myObj;
    A()
    {
        myObj = nullptr;
    }
    ~A()
    {
        if(myObj)
        {
            delete myObj;
            myObj = nullptr;
        }
    };
    
    void myFunc(Obj* o)
    {
        myObj = o;
    }
};

int main()
{
    A* a = new A();
    a->myFunc(new Obj());
    a->myObj->increment();
    delete a;
}

Just as a hypothetical .... regarding the above code - specifically the line

a->myFunc(new Obj());

It compiles fine, but is there anything functionally wrong with doing this? Other than maybe poor form, or going against best practices?

Upvotes: 0

Views: 74

Answers (1)

Mr.C64
Mr.C64

Reputation: 42984

An important problem with your code is that it's very fragile and bug-prone.

For example, what happens if you have two instances of class A, that point to the same Obj instance?

Suppose that one of the A instances is deleted. Then the object pointed by myObj is destructed. But now the other instance of A has a raw pointer that is pointing to a memory that is not valid anymore.

A better way of storing object pointers, assuming shared ownership semantic, is to use a smart pointer like std::shared_ptr.

For example, in class A replace the raw pointer Obj* myObj with a smart pointer like std::shared_ptr<Obj>, and don't explicitly invoke delete myObj from the A's destructor. Instead, let the std::shared_ptr's destructor automatically handle the deletion of the smart pointer data member. What will happen under the hood is that shared_ptr will use a reference count to figure out when there are no more references to the pointed object, and when this reference count goes to zero, the pointed object will be deleted.

Upvotes: 1

Related Questions