【问题标题】:What's the equivalent of C++ `const` return types in DelphiDelphi中C++`const`返回类型的等价物是什么
【发布时间】:2013-09-12 14:42:12
【问题描述】:

我有以下 C++ 代码:

标题:(在类内)

virtual const bigint &getPopulation() ;

实现:

static bigint negone = -1 ;
const bigint &hlifealgo::getPopulation() {
   // note:  if called during gc, then we cannot call calcPopulation
   // since that will mess up the gc.
   if (!popValid) {
      if (inGC) {
        needPop = 1 ;
        return negone ;
      } else {
        calcPopulation(root) ;
        popValid = 1 ;
        needPop = 0 ;
      }
   }
   return population ;
}

我将它移植到 Delphi,它工作得很好。 我仍然对 const 返回类型有点困惑。

我可以忽略翻译中的const,还是这里有什么要注意的?

这个概念在 Delphi 中有类似物吗?

【问题讨论】:

  • 我假设 BigInt 通过引用传递(因为它是 32 位代码并且通过引用传递 64 位值更快)并且 const 防止它被更改。
  • 类型是const bigint& 所以是的,它是一个参考
  • 在这种情况下,等效项是:procedure getP(var population: int64);,但 var 引用是 const (如果有意义的话)
  • 这并不等同,约翰。在 C++ 中,调用者可以将结果存储在 const 引用变量中。对该函数返回的population 变量的任何进一步修改也可以在该other const-reference 变量中观察到。为了模仿这种行为,您需要 function getP: PInt64 并承诺调用者不会使用该指针来修改指向的数据。底线是 Delphi 没有将 const 作为 type 一部分的概念。
  • @RobKennedy,好的,我现在明白了,& 使函数返回一个指针(通过引用传递),因为它确实是一个指针,需要 const 以防止您丢失它。

标签: c++ delphi


【解决方案1】:

在 Delphi 中没有类似的东西。您在这里拥有的是const 参考。 Delphi 没有区分可变引用和常量引用的机制。所有的引用都可以用来改变一个对象。所以这不是与const 返回类型相关的问题,更多的是Delphi 不支持常量引用。

在将代码从 C++ 移植到 Delphi 时,您别无选择,只能忽略 const 引用。在 Delphi 中你无法区分不同类型的引用,只有一种。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-09
    • 2019-05-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多