创建临时对象时不调用Ctor

时间:2018-08-09 08:44:21

标签: c++ polymorphism temporary-objects

class Base
{
public:
    Base() { cout << "base constructor" << endl; }
    virtual ~Base() { cout << "base destructor" << endl; }
    virtual void hello() { cout << "hello Base" << endl; }
};

class Derived : public Base
{
public:
    Derived() { cout << "derived constructor" << endl; }
    virtual ~Derived() { cout << "derived destructor" << endl; }
    virtual void hello() { cout << "hello Derived" << endl; }
};

Derived* d = new Derived();
cout << "-------------------" << endl;
{
    static_cast<Base>(*d).hello();

    Base b = static_cast<Base>(*d);
    b.hello();
}

result
base constructor
derived constructor
-------------------
hello Base
base destructor
hello Base
base destructor

如上所示,调用了dtor但未调用ctor。调用dtor意味着创建了一个临时对象,但是为什么不调用ctor?是否复制内存本身以进行优化? (没有ctor调用)

0 个答案:

没有答案