c++ - 是否可以使用非常量指针调用非常量函数,以及当两个 unique_ptr 指向同一个对象时程序将如何运行?

标签 c++ oop c++17 unique-ptr dynamic-cast

第一个问题:

现在我有两个 unique_ptr(ptrToBaseptrToDerived)指向同一个对象(由 make_unique).那么程序行为是未定义的还是如何销毁两个指针?

第二个:

指针 as_const(ptrToDerived) 是 constatn。尽管 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;
}

最佳答案

So is the program behavior undefined or how will it work on destroying the two pointers?

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

the pointer as_const(ptrToDerived) is constatn. how function2 can be called although it's a non-constant function

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();

关于c++ - 是否可以使用非常量指针调用非常量函数,以及当两个 unique_ptr 指向同一个对象时程序将如何运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59697936/

相关文章:

c++ - 错误 luaL_doString "unexpected symbol near '/' "

c++ - 如何在 visual studio 中使用处理器寄存器?

swift - 函数和返回值

c++ - std::initializer_list{x, y, z} (CTAD) 有效吗?

c++ - 在 switch 语句中分配 lambda

Visual Studio 2008 Express Edition 中的 C++ 第一个程序

c++ - 来自 WMI 的 nVidia 驱动程序版本不是我想要的

java - 关于按引用或值传递的概念

c# - 当我想拥有一个基本接口(interface)并从中实现时,调用在以下方法或属性之间不明确

c++ - SFINAE : Delete a function with the same prototype