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

时间:2015-05-12 23:37:23

标签: c++ class object

So I have the following class...

- (void)SOAPManager:(SOAPManager *)client didSuccesWithoutError:(id)responseObject
{
SearchResult *result = [SearchResult new];
result.myArray = [responseObject allValues];
self.Result = result;
NSLog(@"Loaded successfully: %@", result.retailers);

}

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

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;
};

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?

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

2 个答案:

答案 0 :(得分:4)

Assuming you mean

template <class T1, class T2, class R1, class R2>
struct make_mult_operation {
    typedef MultOperation<T1, T2, typename boost::common_type<R1, R2>::type> type;
};

template <typename T1, typename T2,  typename R2>
typename boost::disable_if<is_some_kind_of_Base<T1>,
                make_mult_operation<Terminal<T1>, T2, T1, R2> >::type::type
operator*( T1 const& u, Base<T2, R2> const& v) { /* ... */ }

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

nullptr

and later assign it an instance of Pet* pet = NULL; // or nullptr :

Pet

This allows you to check the value of pet = new Pet(0, "Henry"); without invoking undefined behaviour (through uninitialised variables):

pet

答案 1 :(得分:0)

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

With your code

delete my_pet;

no dynamic memory allocation was involved, thus you don't ever need to call Pet my_pet = Pet(0, "Henry");

The object instance will be destroyed as soon the scope where you called delete my_pet; 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 Pet my_pet = Pet(0, "Henry"); and bothering about forcing deletion yourself.

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

Pet