可以使用非常量指针调用非常量函数,当两个unique_ptrs指向同一对象时,程序将如何运行?

问题描述 投票:0回答:1

第一个问题:

现在我有两个unique_ptrptrToBaseptrToDerived)指向同一个对象(由make_unique制成)。那么程序行为是未定义的,还是在销毁两个指针时如何工作?

第二个:

指针as_const(ptrToDerived)为常量。 function2是非恒定函数,但如何调用]

#include <iostream>
#include<vector>

using namespace std;
class Base{

    public:
    virtual void function()const{
        cout<<"\n"<<__FUNCSIG__;
    }

    virtual~Base(){cout<<"\n"<<__FUNCSIG__;}
};




class Derived : public Base
{

    public:
    int var{9};

    virtual void function()const override{
        cout<<"\n"<<__FUNCSIG__<<"\nvar: "<<var;
    }
    void function1()const{
        cout<<"\n"<<__FUNCSIG__;
    }

    void function2(){
        cout<<"\n"<<__FUNCSIG__;
    }

    virtual~Derived(){cout<<"\n"<<__FUNCSIG__;}
};



int main()
{

    //ptr of type Base* pointing to an object of type of Derived 
    unique_ptr<Base> ptrToBase {make_unique<Derived>()};

    unique_ptr<Derived> ptrToDerived {dynamic_cast<Derived*>(ptrToBase.get())};
    if (ptrToDerived) ptrToDerived->function1();

    as_const(ptrToDerived)->function2();

    return 0;
}
c++ oop c++17 unique-ptr dynamic-cast
1个回答
2
投票

那么程序行为是未定义的,还是在销毁两个指针时如何工作?

是的,由于双重破坏,它拥有UB。不要这样做。

指针as_const(ptrToDerived)是constatn。尽管它是非恒定函数,但如何调用function2

std::as_const将使它成为const std::unique_ptr<Derived>而不是std::unique_ptr<const Derived>,这就是调用function2()的原因。

另一方面,这将不起作用:

unique_ptr<const Derived> ptrToDerived{dynamic_cast<Derived*>(ptrToBase.get())};

ptrToDerived->function2();

可能的编译器输出:

source>:41:29: error: passing 'const Derived' as 'this' argument discards qualifiers [-fpermissive]

   41 |     ptrToDerived->function2();
© www.soinside.com 2019 - 2024. All rights reserved.