Pages - Menu

標籤

AWS (1) bash (1) Boost (2) C (2) CMake (2) Concurrency_Programming (3) CPP (37) Database (2) DNS (1) Docker (4) Docker-Compose (1) ELK (1) emacs (4) gcp (1) gdrive (1) git (1) gitbash (2) gitlab (1) kvm (4) Linux (5) MT4 (4) MT5 (4) Multicast (2) MySQL (2) Nijatrader8 (1) OpenCV (1) Python (4) QT5 (1) R (1) rdp (3) screenshot (1) ssh (3) Tabnine (1) TCP (1) TensorFlow (1) Tools (12) Ubuntu_1904 (11) Ubuntu_20_04 (5) UDP (1) VS2010 (1) VS2015 (1) VS2019 (1) WebServer (1) Win10 (1) winmerge (1) WSL (1) xrdp (1)

搜尋此網誌

2020年5月1日星期五

Simple SmartPointer for Linux

Aim

This is a simple example of Smart Pointer in C++ for Linux. In case your project cannot support std library shared_ptr. You may try this one.

Source



#include <iostream>

#include "SmartPointer.h"

class Foo
{
public:
    Foo() { std::cout << "Hello from constructor" << std::endl; }
    ~Foo() { std::cout << "Hello from destructor" << std::endl; }

    void Print() { std::cout << "Hello from Foo" << std::endl; }
};
class BaseClass
{
public:
    BaseClass() { std::cout << "Hello from BaseClass constructor" << std::endl; }
    virtual ~BaseClass() { std::cout << "Hello from BaseClass destructor" << std::endl; }

    virtual void Print() {}
};
class ChildClass : public BaseClass
{
public:
    ChildClass() { std::cout << "Hello from ChildClass constructor" << std::endl; }
    ~ChildClass() { std::cout << "Hello from ChildClass destructor" << std::endl; }

    // override
    void Print() { std::cout << "Hello from ChildClass Print" << std::endl; }
};

void SimpleCase()
{
    {
        SmartPointer<Foo> foo = MakeSmartPointer<Foo>();
        foo->Print();
    }
    std::cout << "Hello from END" << std::endl;
}
void InheritCase_Print(SmartPointer<BaseClass> p)
{
    SmartPointer<BaseClass> pp = p;
    std::cout << "Print from Base ";
    pp->Print();
    std::cout << "Hello from END" << std::endl;
}
void InheritCase()
{
    std::cout << std::endl;
    SmartPointer<BaseClass> base = StaticCast<BaseClass>(MakeSmartPointer<ChildClass>());
    InheritCase_Print(base);
    SmartPointer<ChildClass> child = DynamicCast<ChildClass>(base);
    child->Print();
    std::cout << "Hello from END" << std::endl;
}
int main (int argc, char *argv[])
{
    SimpleCase();
    InheritCase();

    return 0;
}

Output

$ ./src/SmartPointer 
Hello from constructor
Hello from Foo
Hello from destructor
Hello from END

Hello from BaseClass constructor
Hello from ChildClass constructor
Print from Base Hello from ChildClass Print
Hello from END
Hello from ChildClass Print
Hello from END
Hello from ChildClass destructor
Hello from BaseClass destructor

沒有留言:

發佈留言