C++ - Pointers Question

05/02/2012 07:39 xBlackPlagu3x#1
So I've been studying C++ for the past couple of days, and I'm now on pointers... So like when you pass by value, technically you are having to use double the resources than when you pass by reference. Could that statement be correct?
05/02/2012 14:08 IAmHawtness#2
Quote:
Originally Posted by xBlackPlagu3x View Post
So I've been studying C++ for the past couple of days, and I'm now on pointers... So like when you pass by value, technically you are having to use double the resources than when you pass by reference. Could that statement be correct?
Not really, it depends on what you're passing. Passing an int pointer compared to an int wouldn't be faster, and would only be reasonable to do if you actually needed to modify the int as a return value of the function.

Passing structures/classes as pointers is usually faster though.
05/02/2012 15:58 xBlackPlagu3x#3
Quote:
Originally Posted by IAmHawtness View Post
Not really, it depends on what you're passing. Passing an int pointer compared to an int wouldn't be faster, and would only be reasonable to do if you actually needed to modify the int as a return value of the function.

Passing structures/classes as pointers is usually faster though.
One of the greatest things that's happened to me in the past 3 days is that I now understand what you're talking about lol. :P Thanks, I'll definitely keep this in mind.
05/02/2012 16:11 Lateralus#4
No, because when the compiler translates passing a simple type to assembly, it's just one instruction more, if the compiler doesn't optimize it (not sure if it does). As IAmHawtness said, passing classes and structs as pointers is usually faster.

To compare C++ with C#, C# passes classes as reference types by default, and simple types and structs as value types, and as you know - to modify a simple type or struct by reference, use the "ref" keyword.
05/02/2012 22:13 Spirited#5
I actually studied the compiler you're using for ANSI C++. Yes. If you create a new function and you don't pass variables by reference, it will copy the value of the passing variables to new locations in memory (with the exception of few data types). Arrays are always passed by reference. Structs can be passed by value but it's costly if the structure is large and you're using the function in something like a search. Pointers are alternatives for passing structs by value. If you pass the pointer of a struct, that's more efficient than passing the entire struct.