Ricky
Ricky

Reputation: 883

How do I check if an Object has been initialized/created in C++?

So I have the following class...

class Pet
{
    public:
        Pet() : id(0),
            name("New Pet")
        {

        }

        Pet(const int new_id, const std::string new_name) : id(new_id),
            name(new_name)
        {

        }

        Pet(const Pet new_pet) : id(new_pet.id),
            name(new_pet.name)
        {

        }
    private:
        const int id;
        const std::string name;
};

Somewhere in my code I then create a instance of this class like so...

Pet my_pet = Pet(0, "Henry");

Later on in my code, an event is supposed to cause this pet to be deleted. delete(my_pet);

How do I check if my_pet has been initialized...

Would something like this work?

if(my_pet == NULL)
{
    // Pet doesn't exist...
}

Upvotes: 5

Views: 17912

Answers (3)

Dmitry
Dmitry

Reputation: 704

Something like this?

template<typename T>
void CheckDependency(const T& dependency) {
    if(dependency == nullptr) {
        throw std::runtime_error("Not created" + std::string{typeid(dependency).name()});
    }
}

Upvotes: 0

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

delete(my_pet); doesn't make sense, neither by the signature used (should be delete my_pet;, if valid).

With your code

Pet my_pet = Pet(0, "Henry");

no dynamic memory allocation was involved, thus you don't ever need to call delete my_pet;

The object instance will be destroyed as soon the scope where you called Pet my_pet = Pet(0, "Henry"); is left.


As for your comment "How would I go about forcing the deletion of the pet.", you should use dynamic memory management smart pointers, rather calling new Pet() and bothering about forcing deletion yourself.

If you really need dynamic memory allocation for Pet, rather use something like

std::unique_ptr<Pet> my_pet(new Pet(0, "Henry"));`

Upvotes: 0

Levi
Levi

Reputation: 1983

Assuming you mean

Pet* my_pet = new Pet(0, "Henry");

instead of Pet my_pet = Pet(0, "Henry");
You can initialise your Pet object to NULL (or nullptr for C++11) like so:

Pet* pet = NULL; // or nullptr

and later assign it an instance of Pet:

pet = new Pet(0, "Henry");

This allows you to check the value of pet without invoking undefined behaviour (through uninitialised variables):

if (pet == NULL) // or nullptr
{
    ...
}

Upvotes: 11

Related Questions