'const ref'和'in'之间的区别? [英] Difference between 'const ref' and 'in'?

查看:142
本文介绍了'const ref'和'in'之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解 const ref in 之间的区别,特别是在性能方面。

I'm trying to understand the difference between const ref and in, specially when it comes to performance.


  1. 我知道中的等效于 const scope ,但是 scope存储类意味着什么不能对参数中的引用进行转义(例如,分配给全局变量)。表示?欢迎使用示例代码。

  1. I know that in is equivalent to const scope, but what does the scope stor­age class means that ref­er­ences in the pa­ra­me­ter can­not be es­caped (e.g. as­signed to a global vari­able). mean? example code is welcome.

如何确定 const ref 中实现功能?我知道使用 ref 不会复制对象,因为它是一个引用,但是对于 in 也是一样吗?

How do I decide between const ref and in when implementing a function? I know with ref the object doesn't get copied because it's a reference, but is the same true with in?


推荐答案

1)作用域参数存储类意味着不允许您转义对参数的引用。示例:

1) the scope parameter storage class means that you're not allowed to escape a reference to the parameter. Example:

Object glob;

struct S
{
    Object o;
    void foo(scope Object o)
    {
         this.o = o; // Not allowed! 'o' must not be escaped
         glob = o; // ditto
    }
}

请注意DMD并不是很擅长检测到这一点。上面的示例当前可以编译,但不允许编译。

Note that DMD is not very good at detecting this. The above example currently compiles, but is not allowed.

作用域对于委托参数最有用:

scope is most useful for delegate parameters:

void foo(scope void delegate() dg)
{
    /* use dg */
}

void main()
{
    int i;
    foo({ ++i; });
}

在上面的示例中,甚至不需要为匿名函数分配闭包尽管它具有较高的价值,因为 foo 保证(这是编译器的工作...),该委托没有被转义。 DMD当前确实实现了这种优化。

In the above example, no closure needs to be allocated for the anonymous function even though it has an upvalue, because foo "guarantees" (it is the compiler's job...) that the delegate isn't escaped. DMD currently does implement this optimization.

2)我想的想法是,当 const 和<$ c使用$ c> scope 时,编译器理论上可以按引用或随意传递值,这就是 in 快捷方式有用的原因。 DMD现在没有利用此功能,但它仍然是一个方便的快捷方式,并且具有一定的文档价值。

2) I think the idea is that when both const and scope is used, the compiler could theoretically pass by reference or value at will, which is why the in shortcut is useful. DMD doesn't take advantage of this right now, but it's a handy shortcut nevertheless, and it has some documentation value.

简而言之, in除非用于委托,否则当前不会获得任何性能。 ref 可以通过大型结构或静态数组获得一些性能。当出于性能原因使用 ref 时,通常使用 const 记录(并强制执行) ref 用于更新原始值。

In short, in won't currently gain you any performance unless it's used on a delegate. ref can gain you some performance with large structs or static arrays. When ref is used for performance reasons, const is often used to document (and enforce) that the ref is not used to update the original value.

这篇关于'const ref'和'in'之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆