将指针转换为参考,成本高昂? [英] Converting a Pointer to Reference, Costly?

查看:124
本文介绍了将指针转换为参考,成本高昂?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:


如果我有一个指向一个对象的指针,让我们说 Object * ptr; ,我想传递给一个方法 void foo(Object& obj)我明白我需要写:

  foo(* ptr); 

但是为什么dereference ptr ?只是把它传递 foo(ptr); 不是有意义的吗?我担心 * ptr 可能会对原始对象进行复制,或者至少不要将其传递给 foo 要处理的地址。



任何人都可以为我清除这个地址吗?传递 * ptr 一个潜在的瓶颈,对于代码,希望这行动的速度就像函数 void foo(Object * obj) ; 并通过 foo(ptr)

解决方案>

是否通过 * ptr 是否进行复制取决于被调用的函数是否期望一个 Object 对象&



在前一种情况下,将创建一个副本。在后一种情况下(即您的情况),将会进行复制。


Possible Duplicate:
How expensive is it to dereference a pointer in C++?

If I've got a pointer to an object, let's say Object *ptr;, and I want to pass that to a method of the form void foo(Object& obj) I understand that I need to write:

foo(*ptr);

But why dereference ptr? Wouldn't it make sense to just pass it foo(ptr);? I'm worried *ptr might be making a copy of the original object, or at the least not merely passing to foo the address to work with.

Can anyone clear this up for me? Is passing *ptr a potential bottleneck, for code that expects this to behave just as fast as if the function had been void foo(Object *obj); and called via foo(ptr)?

解决方案

Whether passing *ptr does make a copy or not depends on whether the called function expects an Object or an Object &.

In the former case, a copy would be made. In the latter case (i.e., your case), no copy would be made.

这篇关于将指针转换为参考,成本高昂?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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