Creating Factory

We often make_shared to create a shared pointer in std. It’s safe and easy for the developer to use.
The using examples are in the following code snippet.

    shared_ptr<Base> ptr = make_shared<Base>();
    auto p = make_shared<int>(100);
    cout << *p << endl;

Delete Function

Create a delete function for a class object if we use shared_ptr, then we can define our way how to release the memory we had took.

#include "cat.h"

using namespace std;

void deleteCatObjest( Cat *__cat )
{
    cout << "delete cat" << endl;
    delete __cat;
}

int main()
{
    shared_ptr<Cat> p( new Cat(), deleteCatObjest );
    return 0;
}

Use shared_ptr to manage the FILE pointer.

    FILE *ptr = fopen("/Users/weiyang/code/simpleCPP/main12.cpp", "r");
    if( ptr )
    {
        shared_ptr<FILE> fp( ptr, fclose );
        // ...
    }
    else
    {
        perror("main12.cpp Open failed ");
    }

output:

main12.cpp Open failed : No such file or directory

Use dynamic_cast

The CPP operator dynamic_cast is used in a polymorphic scene, which means basic class needs virtual function. It has data type check function, the pointer will be nullptr if cast failed.

using namespace std;

class Base
{
public:
    Base(){  m_Name = "Base";  };
    virtual void show()
    {
        cout << "Base: " << m_Name << endl;
    }
protected:
    string m_Name;
};

class Drive1: public Base
{
public:
    Drive1(){ m_Name = "Drive1"; };
    virtual void show()
    {
        cout << "Drive1: " << m_Name << endl;
    }
};

int main()
{
    Base *bPtr = new Base(); //Drive1
    auto ptr = static_cast<Drive1*>( bPtr );
    printf( "ptr: %p\n", ptr );
    ptr->show();
    auto ptr1 = dynamic_cast<Drive1*>( bPtr );
    printf( "ptr: %p\n", ptr1 );
    return 0;
}

/*
ptr: 0x7fdfb2d05060
Base: Base
ptr: 0x0
*/

It’s not recommended to use dynamic_cast directly for shared pointer. shared_ptr provides a few new cast functions such as dynamic_pointer_cast<T>() and static_pointer_cast<T>(), they return new shared_ptr object.

int main()
{
    shared_ptr<std::exception> p0( new bad_exception );
    auto p1 = dynamic_pointer_cast<bad_exception>( p0 );
    auto p2 = static_pointer_cast<exception>( p1 );
    printf( "p1: %p\n", p1.get() );
    printf( "p2: %p\n", p2.get() );
    return 0;
}

/*
p1: 0x7fdc56f02250
p2: 0x7fdc56f02250
*/
Categories: CPlusPlus

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments

Tex To PDF
: convert the Latex file which suffix is tex to a PDF file

X
0
Would love your thoughts, please comment.x
()
x