How to safely check if the a class has been instantiated in C++?

Oh damn it I'm so stupid :-(,I could just use a bool array to reach the purpose

For example,I recieved a pointer p_class;

So how do I check if p_class points to a instantiated class?

I mean,even if the class was not been instantiated,every function of the class can still be called;and if I tried to access a variable in the class,I may access some illegal address and the program will crash

Well,I'm trying to write a network lib. Since there are many protocols the lib have to support,

the_lib
{
public:
    int selectProtocol(prtcl/*an enum*/ p)
    {
        switch(p)
        {
        case tcp:
            t=new tcp;
        ....
        }
    }
    int setTCP(opt,para)
    {
    switch(opt)
        {
        case csum:
            t->setcsum(para)
            break;
            ....
        }
    int setUDP(opt,para);
    ....

private:
    TCP *t=0;
    UDP *u=0;
    ...
}

Thus if the user select UDP at first but call setTCP, I have to determine whether to actually call the function in class TCP or not

Answers


You can solve your problem by not using a bare pointer, and using a smart pointer instead. Both std::unique_ptr<> and std::shared_ptr<> have bool conversion operators that allow you to test if the pointer is valid or not.

class Foo { /* ... */ };

void foo (const std::unique_ptr<Foo> &p) {
    if (!p) { /* ... */ }
}

void foo (const std::shared_ptr<Foo> &p) {
    if (!p) { /* ... */ }
}

std::unique_ptr<Foo> p(new Foo);
std::shared_ptr<Foo> q = std::make_shared<Foo>();

If you are not performing dynamic allocation, then avoid pointers, and pass your object around to functions that take references.

void foo (const Foo &f) {
    //...
}

0. The best thing to do? Don't use pointers.
MyClass instance;
instance.do_something();   // guaranteed to be safe to call

But if you need to refer to some object, then use references! In a well-formed piece of code, references are guaranteed to be pointing to some object, and thus any method you wish to call are guaranteed safe to be called.

But in those cases where you really need to use pointers, then:

1. Don't use raw pointers. Use smart pointers.

std::unique_ptr is almost always the best smart pointer for most of your cases. If you need shared semantics, then use std::shared_ptr. But remember: always prefer std::unique_ptr.

The good thing with most smart pointers is that they already do some default initialization for you when they are constructed without being initialized. Mostly, they set their internal pointer representation to nullptr.

2. Don't need ownership of an object? Just want to keep a reference but want to be able to set nullptr?

Use boost::optional<T&>. boost::optional has a specialization for references whose interface is very much like that of a pointer, but only much safer, as it does the same initialization technique as those of smart pointers.

3. Really need to use raw pointers for some unimaginable reason? Then always set it to nullptr when it's not meant to point to some object.
MyClass* p_instance = nullptr;
// Use p_instance, perhaps assign to it
p_instance = nullptr;   // You don't need to use the pointed-to object

The gist of the above three techniques is this: because a pointer with a value of nullptr does not point to some valid object, then you can use it to check whether the pointer points to a valid object or not.

In this way your code can check if it's not initialized (p_instance == nullptr) or not (p_instance != nullptr). Also, the use of nullptr increase your chances of getting a runtime error when doing something on an invalid object, though the behavior is very much implementation dependent.

The general pattern for checking and using a pointer would be:

if(ptr) {
   ptr->do_something();
}
But what if you really, really need to call do_something()? Then we are back to rule zero. :)

Need Your Help

the next best easy data storage after plain text?

ios ios5

I'm looking for a storage format for some structured data.

how to get a variable over to a function?

javascript jquery

i want to get a variable (which is set when a link is clicked) over to a function and show it as a pop out.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.