Can you give me an example when I can't pass argument by reference and I need to use pointer. I've found an example, but I'm not sure.
Suppose you have a class D derived from the base class B. You need pointer if you want do so:
void function(B* b){...}
int main{
D* d;
function(d);
}
The single time where you can not use a reference and must use a pointer is if you allow the concept of "no argument" by passing a null pointer.
However, you might want to use pointers as arguments when you are actually storing a pointer to whatever was passed. Most C++ developpers will notice that you aren't using a reference and pay special attention to what your documentation says.
If there is a coding guideline (like Google's) that says to use pointer arguments, then that's what you do.
Otherwise, only declare your own function with pointer formal argument when
a nullpointer is a valid & meaningful actual argument, or
the actual argument is most naturally pointer already, or
you're going to store that pointer somewhere.
Possibly more cases, but I think you get the drift: when you have a choice (no coding guideline saying otherwise), prefer references.
Cheers & hth.,
Another case: if the thing you're passing is the last argument before varargs:
void fn1(A &a, ...); // Uh oh
void fn2(A *a, ...); // Good
I don't know if this is required by the standard, or is just a bug in the implementation of the C++ compiler I use.
Typically, you use pointers for one of two things:
Reassignability - you can't rebind a
reference.
Null pointers - there's no such
thing as a null reference.
If your intended use case does not need either of those two properties, use a reference. Else, use a pointer.
If you want to allow the lack of an object, you need to use pointers:
// This allows DoSomething to receive pointers to NULL, which cannot
// be done with references
void DoSomething(Something *pSomething)
{
if (pSomething)
{
...
}
}
int main()
{
Something *pSomething=NULL;
DoSomething(pSomething);
}
http://www.daniweb.com/forums/thread216353.html
Singly linked lists example were pointers and pointer of pointers are used as function parameters.
the only reason is if you need to pass null. I.e you want to call the function saying 'I haven't got one of those'
I think that if you want to pass a function, you have to pass it by pointer. I don't see how you can pass the function by reference.
For example, take the following function:
#include <iostream>
#include "math.h"
void myfun (double value, size_t nofloops, double (*function)(double))
{
std::cout << value << std::endl;
for (size_t i=0;i<nofloops;++i)
{
value = function(value);
std::cout << value << std::endl;
}
std::cout << "------------------" << std::endl;
}
void main()
{
myfun(100,10,sin);
myfun(100,10,cos);
myfun(100,10,sqrt);
}
The function in this small utility executes the given function a number of times, taking the result as input in the next iteration. I can't see how you can pass the function by reference.
Related
Imagine the following scenario:
typedef std::function<float(float)> A;
typedef float(*B)(float);
A foo();
void bar(B b);
You wish to do something along the lines of:
bar(foo());
Obviously this does not work. Mainly because A can contain a state and B is a function pointer. What if we know that A does not contain a state and we wish to somehow take it's "meaning" and put it into something that can be passed for a B?
Is it impossible?
If you can ensure that the callable object stored in A is a function pointer or a lambda with an empty capture list, you can simply get a function pointer in this way:
foo().target<B>();
In general, a std::function can "box" some closure (e.g. the value of some lambda function). And a closure contains both code and data (the closed values). So I believe that you cannot portably convert it to a naked function pointer. BTW, because conceptually closures are mixing code and data languages not providing them (like C) practically requires callbacks (i.e. the convention to pass every function pointer with some additional data, look into GTK for a concrete example).
Some implementation specific tricks might make a trampoline function on the stack (e.g. dynamically generate, perhaps with asmjit, some machine code containing a pointer to the closure, etc.). But this is not portable and system specific (in particular because the stack needs to be executable)
What if we know that A does not contain a state and we wish to somehow take it's "meaning" and put it into something that can be passed for a B?
Even that isn't sufficient. std::function provides a target() member function, that if you know the exact type of the underlying functor, you can get it back. So we can do, for instance:
void print(int i) { std::cout << i; }
std::function<void(int)> f = print;
auto ptr = f.target<void(*)(int)>(); // not null
(*ptr)(42); // works
However, even if our functor f doesn't contain state, that doesn't mean that its underlying type is precisely void(*)(int). It could be a completely different function pointer, in which case we wouldn't be able to pull it out:
int square(int i) { return i*i; }
f = square;
ptr = f.target<void(*)(int)>(); // nullptr!
Or it could be a lambda, in which case we wouldn't even be able to name the type, much less pull it out:
f = [](int i){ std::cout << i; }; // same as print, right?
ptr = f.target<void(*)(int)>(); // ... nope :'(
Basically, type erasure is really type erasure. If you need the original underlying type, that's likely indicative of a bad design.
I am trying to find out using the below code with sort an array in asscending order. And I find method 1,2,3,4 all get the same result:1234.
Which method is the best?
And when and why should should I use pointer /reference? Thanks you.
Using & to call, and * in function parameter
Just used * in function parameter
Just used & in function parameter
nothing:
#include <iostream>
using namespace std;
void swap(int a,int b){
int t;
t=a;
a=b;
b=t;
}
void main(){
int a[]={1,2,3,4};
for (int i=1; i<3; i++)
for (int j=3; j>i;j--)
if(a[j]<a[j-1])
swap(a[j],a[j-1]);
cout << a[0] <<a[1]<<a[2]<<a[3];
}
Your first two versions are identical. They both explicitly pass a pointer in to the function.
Your third version has the same semantics, but different syntax. References can be seen as pointers with nicer syntax.
Your fourth version doesn't actually swap the variables you pass in because you pass by value, so they are copied.
I would prefer the third version as it is clearer.
Generally, references are more of a convenience thing. They allow the programmer to pass objects by reference without explicitly saying they want to do so
For example, this code
// C-style pointers
some_func(int* x, int* y)
{
(*x)++;
(*y)++;
}
...
int x = 5, y = 8;
some_func(&x, &y);
// x == 6 and y == 9
Is effectively equal to this code
// C++-style references
some_func(int& x, int& y)
{
x++;
y++;
}
...
int x = 5, y = 8;
some_func(x, y);
// x == 6 and y == 9
Both achieve the same result.
Also, in the case with classes/structs, references allow you to have direct access to class/struct members without having to type that stupid arrow (->):
class Example
{
public:
Example();
int x;
int y;
}
...
void do_something(Example& ex)
{
ex.x++;
ex.y++;
}
instead of
class Example
{
public:
Example();
int x;
int y;
}
...
void do_something(Example* ex)
{
ex->x++;
ex->y++;
}
Please note that references used in this manner are a C++ feature only (there is no support for this in C). In C++ you have the choice of using either pointers or references, but IMHO references look 'cleaner' and require less typing (thus reducing the risk of RSI).
I don't see a difference between 1. and 2.. But in general:
Passing pointers is passing an address to a variable. Then you modify something under this address using dereference i.e. *a.
Same.
Is passing via reference, it is basically equivalent of passing pointers with nicer syntax. There are of course some "minor" (from a beginner's point of view) differences, such as, you cannot make an empty reference (nullptr).
Is passing by value, which does not operate on original operands but on their copies. At the function call, temporary copies of arguments are made. This means, you won't see changes to the argument outside of the function.
The general order of preference is:
Use references, or const references.
If you need to make a copy of the object anyways, pass by value.
Smart pointers.
Pointers. Normal user should almost never need to resort to this.
Using references is preferred, because c++ prefers value-semantics. In other words, treating things like variables, i.e. not handlers/pointers. So when you pass a variable to a function, you type it naturally, even if you want to change it. You want to use the object, you pass the object. You don't care that under the hood it uses handlers.
Pointers are generally reserved for operations which deal with ownership of objects.
Separating pointers and references in such way makes it possible to express separate semantics with separate syntax. This makes code more readable.
First of all, I would like to point out that you shouldn't have used
int a[]={1,2,3,4};
in your code, because your program will always display 1234 even if your swap function does not work well. Therefore, you should use something like
int a[]={2,4,1,3};
Secondly, method 1 and method 2 are exactly same. There's no difference at all.
Thirdly, method 4 does not work properly, because the data in the array 'a' hasn't been modified. This happens because you have passed the variables 'by value' rather than 'by reference'. You are getting 1234 as output because that's what you have assigned to the array.
Finally, the only choice you have is between 'method 1' and 'method 3'.
I would suggest 'method 3' because it is simpler to use and less prone to confusion (and errors) as compared to 'method 1'.
In some cases, passing by reference allows the compiler to keep a register based variable in that same register in the called function (as opposed to storing the value in local memory and passing an address to that local memory to the called function).
This question already has answers here:
What are the differences between a pointer variable and a reference variable?
(44 answers)
Closed 9 years ago.
Some of methods that I see in C++ code are of this structure:
void Class::method1(int &a);
and are called like this:
int a;
class->method1(a);
But sometimes I see structures like:
void Class2::method2(int* a);
And these methods are called like this:
int a;
class2->method2(&a);
I understand that in the first case the method accepts an address of a variable, and in the second - pointer to a variable, right?
Could someone explain to me what is the difference between these two approaches, and when to use which?
Also, in the first example, it seems that a method can be taking "int& a" or "int a", and in both cases we would call it the same way: int a; class->method1(a); ? This seems confusing.
Thanks.
void Class::method1(int &a);
This is passing by reference.
void Class2::method2(int* a);
This is passing the pointer. In class2->method2(&a);, & is the address of operater.
First one is called using a reference to a variable, second one - using a pointer. There are some difference between the two concepts. I encourage you to google this, but the most important ones I can think of right now are that a reference can not be constructed without pointing to an existing object and that a pointer can be NULL.
void Class::method1(int &a) means you are passing a by reference and the caller can expect a to be modified.
void Class2::method2(int* a) means you are passing a by pointer and the caller can expect the thing to which a points to be modified.
Personally I don't like pass by reference since the caller doesn't quickly know if a will be modified as the calling syntax for pass by reference and pass by value are identical. Passing by constant reference void Class::method1(const int &a) is better still since then a cannot be modified and you can gain an efficiency in not taking value copies if a is a large object.
However many folk differ in their opinion and say that you should pass by pointer if the function allows the pointer to be null; i.e. can your function do something useful without a inputted?
In the first case, the method accept a reference to the variable.
It means that if a is modified inside the method1, it will be modified after the function returns.
In the second case, it accepts a pointer to the variable. A pointer is the memory adress of the variable. It's what the & retrieves : The address (aka a pointer to a).
Both type have essentially the same purpose : Being able to modify a variable of a different scope.
See that example :
void fooPointer (int* pointer) {
*pointer += 1;
}
void fooReference (int& reference) {
reference += 1;
}
int main () {
int a = 0;
std::cout << a; // Ouputs 0
fooPointer (&a);
std::cout << a; // Outputs 1
fooReference (a);
std::cout << a; // Outputs 2
}
As you can see, both allow you to do the same here. But using references is usually easier and more readable, because everything is done implicitly, so you don't have to reference (*) or dereference (&) your variables.
I have a routine that gets passed a void* to a structure. In the
routine I cast it to the correct type, e.g.
SomeFunc(void* pMsg) {
printf("Event = %d\n", static_cast<struct MyEventMsg*>(pMsg)->Event);
}
If I am accessing many members of the structure the code looks pretty
messy. I can create a new pointer of the correct type and assign it
the cast void*, but it seems like it shouldn't be necessary to create
a temporary variable just for this purpose. Is there some way to cast
the parameter pMsg to the correct type?
Thanks
Doug
Creating the pointer of the correct type and assigning it the cast of the void* is the correct way to go. It will make the code shorter and easier to read, if you choose a "good" name for the pointer.
You say that you think the pointer "unnecessary". If this is because you think that there is a run time cost associated with it, you may well find out that the compiler will eliminate the pointer for you.
The way to do what you ask is
SomeFunc(void* pMsg) {
MyEventMsg * pM = static_cast<struct MyEventMsg*>(pMsg);
printf("Event = %d\n", pM->Event);
printf("Something Else = %d\n", pM->SomeOtherMember);
...
}
But I would recommend something more C++:
SomeFunc(MyEventMsg &Msg) { // consider making this const
cout << "Event = " << Msg.Event << endl;
cout << "Something Else = " << Msg.SomeOtherMember << endl;
...
}
No, as a matter of fact it should be. Static cast is your best option. Don't worry about the temporary. It will most likely be optimized away by your compiler
Just go with the temporary. If you manage everything properly (if any managing is even needed), it won't cause you any problems. I'd imagine making the temp will be faster as well since you'd only be making one cast as opposed to casting EVERYTIME for EVERY member of the struct.
The first question is why does the function take a void* in the first place. If that is changed to the exact type of pointer, then the problem goes away altogether.
If you are going to use the pointer (after casting to the appropriate type) more than once in the function, I would just create a local variable of the given type, cast once and then use it. As of the cost of creating such a variable, in many cases the compiler will optimize the variable away (if you doubt, look at the generated assembly).
but it seems like it shouldn't be necessary to create a temporary variable just for this purpose
Um, it's not: like you said, you can do a cast in-place.
Make your choice: cast every time (messy) or cast once into a variable of the correct type (clean).
Change the type of pMsg to struct MyEventMsg * and create a second, inline version of the method that takes a void *, casts it and calls the first one.
You can prevent calls to the first method by making it private.
I've mostly only worked with C and am running into some unfamiliar issues in C++.
Let's say that I have some function like this in C, which would be very typical:
int some_c_function(const char* var)
{
if (var == NULL) {
/* Exit early so we don't dereference a null pointer */
}
/* The rest of the code */
}
And let's say that I'm trying to write a similar function in C++:
int some_cpp_function(const some_object& str)
{
if (str == NULL) // This doesn't compile, probably because some_object doesn't overload the == operator
if (&str == NULL) // This compiles, but it doesn't work, and does this even mean anything?
}
Basically, all I'm trying to do is to prevent the program from crashing when some_cpp_function() is called with NULL.
What is the most typical/common way of doing this with an object C++ (that doesn't involve overloading the == operator)?
Is this even the right approach? That is, should I not write functions that take an object as an argument, but rather, write member functions? (but even if so, please answer the original question)
Between a function that takes a reference to an object, or a function that takes a C-style pointer to an object, are there reasons to choose one over the other?
Basically, all I'm trying to do is to
prevent the program from crashing when
some_cpp_function() is called with
NULL.
It is not possible to call the function with NULL. One of the purpose of having the reference, it will point to some object always as you have to initialize it when defining it. Do not think reference as a fancy pointer, think of it as an alias name for the object itself. Then this type of confusion will not arise.
A reference can not be NULL. The interface makes you pass a real object into the function.
So there is no need to test for NULL. This is one of the reasons that references were introduced into C++.
Note you can still write a function that takes a pointer. In this situation you still need to test for NULL. If the value is NULL then you return early just like in C. Note: You should not be using exceptions when a pointer is NULL. If a parameter should never be NULL then you create an interface that uses a reference.
A C++ reference is not a pointer nor a Java/C# style reference and cannot be NULL. They behave as if they were an alias to another existing object.
In some cases, if there are bugs in your code, you might get a reference into an already dead or non-existent object, but the best thing you can do is hope that the program dies soon enough to be able to debug what happened and why your program got corrupted.
That is, I have seen code checking for 'null references' doing something like: if ( &reference == 0 ), but the standard is clear that there cannot be null references in a well-formed program. If a reference is bound to a null object the program is ill-formed and should be corrected. If you need optional values, use pointers (or some higher level construct like boost::optional), not references.
As everyone said, references can't be null. That is because, a reference refers to an object. In your code:
// this compiles, but doesn't work, and does this even mean anything?
if (&str == NULL)
you are taking the address of the object str. By definition, str exists, so it has an address. So, it cannot be NULL. So, syntactically, the above is correct, but logically, the if condition is always going to be false.
About your questions: it depends upon what you want to do. Do you want the function to be able to modify the argument? If yes, pass a reference. If not, don't (or pass reference to const). See this C++ FAQ for some good details.
In general, in C++, passing by reference is preferred by most people over passing a pointer. One of the reasons is exactly what you discovered: a reference can't be NULL, thus avoiding you the headache of checking for it in the function.
You can use a special designated object as the null object in case of references as follows:
class SomeClass {
public:
int operator==(SomeClass &object) {
return (this == &object);
}
static SomeClass NullObject;
};
SomeClass SomeClass::NullObject;
void print(SomeClass &val) {
if(val == SomeClass::NullObject)
printf("\nNULL");
else
printf("\nNOT NULL");
}
You should use NULL only with pointers. Your function accepts a reference and they can't be NULL.
Write your function just like you would write it in C.
C++ references naturally can't be null, you don't need the check. The function can only be called by passing a reference to an existing object.
What is the most typical/common way of doing this with an object C++ (that doesn't involve overloading the == operator)?
Is this even the right approach? ie. should I not write functions that take an object as an argument, but rather, write member functions? (But even if so, please answer the original question.)
No, references cannot be null (unless Undefined Behavior has already happened, in which case all bets are already off). Whether you should write a method or non-method depends on other factors.
Between a function that takes a reference to an object, or a function that takes a C-style pointer to an object, are there reasons to choose one over the other?
If you need to represent "no object", then pass a pointer to the function, and let that pointer be NULL:
int silly_sum(int const* pa=0, int const* pb=0, int const* pc=0) {
/* Take up to three ints and return the sum of any supplied values.
Pass null pointers for "not supplied".
This is NOT an example of good code.
*/
if (!pa && (pb || pc)) return silly_sum(pb, pc);
if (!pb && pc) return silly_sum(pa, pc);
if (pc) return silly_sum(pa, pb) + *pc;
if (pa && pb) return *pa + *pb;
if (pa) return *pa;
if (pb) return *pb;
return 0;
}
int main() {
int a = 1, b = 2, c = 3;
cout << silly_sum(&a, &b, &c) << '\n';
cout << silly_sum(&a, &b) << '\n';
cout << silly_sum(&a) << '\n';
cout << silly_sum(0, &b, &c) << '\n';
cout << silly_sum(&a, 0, &c) << '\n';
cout << silly_sum(0, 0, &c) << '\n';
return 0;
}
If "no object" never needs to be represented, then references work fine. In fact, operator overloads are much simpler because they take overloads.
You can use something like boost::optional.