首页 > 解决方案 > 返回指向意图(in)参数的指针

问题描述

我试图在类的上下文中更好地理解constC/C++ 和intent(in)Fortran 之间的区别。

C++:如果我是成员函数const的隐式this参数并且我返回对成员的this引用,则这些引用必须是const T*. 因此const不仅适用于函数调用的范围,而且还扩展到该函数调用中“创建”的所有引用。

Fortran:如果我是成员函数的参数,则intent(in)仅适用于成员函数的范围。我不能在成员函数内部发生变异,但我可以返回引用并在外部进行修改。thisintent(in)thisthis

如果我在 Fortran 和 C++ 中有以下或多或少等效的 Counter 类代码来测试它,它似乎是正确的。

#include <iostream>


class Counter {
    int val{};

public:
    auto next()
    {
        return val++;
    };

    const auto raw() const
    {
        const auto ptr = &val;
        return ptr;
    };
};

int main()
{
    Counter c{};
    std::cout << c.next() << "\n";
    std::cout << c.next() << "\n";

    auto ptr = c.raw();
    // does not compile, as it is expected
    *ptr = 0;
    std::cout << c.next() << "\n";

    return 0;
}
module counter_mod
    implicit none(type, external)
    private
    public :: Counter_t

    type :: Counter_t
        private
        integer :: val = 0
    contains
        procedure :: next
        procedure :: raw
    end type

contains

    integer function next(this)
        class(Counter_t), intent(inout) :: this
        next = this%val
        this%val = this%val + 1
    end function

    function raw(this) result(res)
        class(Counter_t), target, intent(in) :: this
        integer, pointer :: res
        ! This would be forbidden
        ! this%val = 5
        res => this%val
    end function
end module

program test_raw
    use counter_mod, only: Counter_t
    implicit none(type, external)

    type(Counter_t), target :: c
    integer, pointer :: ptr

    write(*, *) c%next()
    write(*, *) c%next()

    ptr => c%raw()
    ptr = 0
    write(*, *) c%next()
end program

标签: c++pointersfortranlanguage-lawyerimmutability

解决方案


在 c++ 中,您不需要返回 aconst pointer您可以简单地返回 a const reference。这是典型的 getter 实现,例如:

const 方法表示该方法不会修改实例属性。

class Counter {
    int val{};

public:
    auto next()
    {
        return val++;
    };

    const int &getVal const
    {
        return val;
    };
};

在上面的示例中,getter 还可以返回 val 的副本。(在这种情况下不需要返回 const 引用)。


推荐阅读