CArray< int,int>和CArray< int,int&> [英] What's the difference between CArray<int, int> and CArray<int, int&>?

查看:310
本文介绍了CArray< int,int>和CArray< int,int&>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于CMap,CList和几乎所有使用模板的东西都是一样的(我猜)。

Same for CMap, CList, and pretty much everything that uses templates (I guess).

我觉得使用模板有点难。这是真的,对于类等等,< class,class&> 形式通常是你想要的,但对于基本类型如 int float 等,这种形式是首选吗?

I find it a bit hard to understand when to use which. It's true that for classes and such, the <class, class&> form is usually what you want, but for basic types like int, float, etc., which form is preferred?

推荐答案

我会说如果你真的不需要别的东西,只需使用 CArray< Type> ARG_TYPE 将是其默认 const TYPE& 。实际上使用 Type& 作为 ARG_TYPE 不是一个好主意。这理论上允许 CArray 修改传递给相应方法的对象/值。当然 CArray 不会这样做,但最好是安全。

I would say that if you don't really need something else, just use CArray<Type> and ARG_TYPE would be its default const TYPE&. Actually using Type& as ARG_TYPE is not a good idea. This theoretically allows CArray to modify the object/value you passed to the corresponding method. Of course CArray doesn't do anything like this but it is better to be on the safe side.

如果您将看到MS VC中可用的源代码,您会看到 ARG_TYPE 在几个方法中用作参数的类型,该参数为某些元素保存新值(INT_PTR nIndex,ARG_TYPE newElement)
INT_PTR添加(ARG_TYPE newElement)数组的数组,如

If you look at the source code that is available within MS VC, you'll see that ARG_TYPE is used in a few methods as type for argument that holds new value for some element(s) of the array such as

void SetAt(INT_PTR nIndex, ARG_TYPE newElement)
INT_PTR Add(ARG_TYPE newElement)
void SetAt(INT_PTR nIndex, ARG_TYPE newElement)
void InsertAt(INT_PTR nIndex, ARG_TYPE newElement, INT_PTR nCount = 1)

如果你在类型 const类型& 之间进行选择,只有受影响的事情是多少次和将复制哪些数据。当值通过引用传递时,只有指向它的指针实际上被传递。这对于对象(附加调用复制构造函数)非常重要,但对于简单类型并不重要。当然你可以尝试通过强制复制 char short 来保存一些字节,它小于相应的指针/ 64位,取决于平台),但我不认为这真的值得额外的麻烦。正如我之前说的,我认为使用默认 CArray< Type> 是一个很好的方法,除非你真的有理由改变它。

If you making your choice between Type and const Type&, then the only thing that is affected is how many times and which data would be copied. When value is passed by reference, only pointer to it is actually passed. This is really important for objects (additional call of copy constructor) but doesn't really matter for simple types. Of course you can try to save a few bytes by forcing copying char or short that is smaller than corresponding pointer (32/64 bit depending on platform) but I don't think that this really worth additional troubles. As I said before, I think that using default CArray<Type> is a good way unless you really have reasons to change it.

这篇关于CArray&lt; int,int&gt;和CArray&lt; int,int&amp;&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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