【C++】 55 经典问题解析 四 new与malloc的区别 dynamic_cast是继承相关的专用转换关键字

关于动态内存分配

new关键字和malloc函数的区别

new关键字是C++的一部分

malloc是由C库提供的函数

new以具体的类型为单位进行内存分配

malloc以字节为单位进行内存分配

new在申请内存空间时可以进行初始化

malloc仅根据需要申请定量的内存空间

例:

#include <iostream>
#include <string>
#include <cstdlib>

using namespace std;

class Test
{
    int* mp;
public:
    Test()
    {
        cout << "Test::Test()" << endl;
        
        mp = new int(100);
      
        cout << *mp << endl;
    }
    ~Test()
    {
        delete mp;
        cout << "~Test::Test()" << endl;
    }
};

int main()
{
    Test* pn = new Test;
    Test* pm = (Test*)malloc(sizeof(Test));  //malloc不能动态内存分配
    
    delete pn;
    free(pm);
    
    return 0;
}

输出:

Test::Test()
100
~Test::Test()

new和malloc的区别

new在所有C++编译器中都被支持

malloc在某些系统开发中是不能调用

new能够触发构造函数的调用

malloc仅分配需要的内存空间

对象的创建只能使用new

malloc不适合面向对象开发

Slide8.PNG

关于虚函数

构造函数不可能成为虚函数

在构造函数执行结束后,虚函数表指针才会被正确初始化

析构函数可以成为虚函数

Slide13.PNG

#include <iostream>

#include <string>



using namespace std;



class Base

{

public:

    Base()

    {

        cout << "Base::Base()" << endl;

    }

    

    virtual ~Base()

    {

        cout << "Base::~Base()" << endl;

    }

};



class Derived : public Base

{



};



int main()

{

    Base* p = new Base;

    

    Derived* pd = dynamic_cast<Derived*>(p);

    

    if( pd != NULL )

    {

        cout << "pd = " << pd << endl;

    }

    else

    {

        cout << "Cast error!" << endl;

    }

    

    delete p;

    

    return 0;

}

输出:

Base::Base()
Cast error!
Base::~Base()

![上传中...]()

评论

暂无评论