c++ - 返回指向意图(in)参数的指针
问题描述
我试图在类的上下文中更好地理解const
C/C++ 和intent(in)
Fortran 之间的区别。
C++:如果我是成员函数const
的隐式this
参数并且我返回对成员的this
引用,则这些引用必须是const T*
. 因此const
不仅适用于函数调用的范围,而且还扩展到该函数调用中“创建”的所有引用。
Fortran:如果我是成员函数的参数,则intent(in)
仅适用于成员函数的范围。我不能在成员函数内部发生变异,但我可以返回引用并在外部进行修改。this
intent(in)
this
this
如果我在 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++ 中,您不需要返回 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 引用)。
推荐阅读
- html - 开关组件,无法实现不同灰度的线条
- counter - 一致的编号图形和 Ascii 艺术图形
- c# - 为什么在尝试获取包含每个结果的链接的搜索结果面板时出现此错误?
- javascript - 使用 Promise.all() 并行更新 Firestore 文档
- swift - swiftui - 如何避免“无法同时满足约束”错误?
- java - 在框架中使用 Android NDK
- android - ShapeableImageView 有黑色覆盖
- php - Doctrine ORM:复合键和外键作为主键
- javascript - 每个循环通过结果集的 SSIS
- python - Python网页抓取用facebook账号登录