第一个问题:
现在我有两个unique_ptr
(ptrToBase
和ptrToDerived
)指向同一个对象(由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;
}
那么程序行为是未定义的,还是在销毁两个指针时如何工作?
是的,由于双重破坏,它拥有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();