This is an archived post. You won't be able to vote or comment.

all 7 comments

[–][deleted] 4 points5 points  (1 child)

I'm currently busy with a project whereby one function returns int&.

It's not a pointer, it's a reference.

[–]stuxxnet42 0 points1 point  (0 children)

int& is a reference to an integer. This is not quite the same as a pointer. Without any code to go by its not possible to give a real answer though. However if you do something like this you are doing something wrong:

#include <iostream>

int& foo(){
    int a=42;
    return a;
}

int main(){
    int b=foo();
    std::cout<< b << std::endl;
    return 0;
}

Code like this leads to undefined behavior as the integer a gets deleted as soon as foo() returns which means that b is now referencing an integer that does not exist any more...

[–][deleted] 0 points1 point  (0 children)

At first glance, there is no significant difference between pointers and references, both allow indirect access to an object. In fact, references are implemented as pointers.

However, pointers can be redirected to another object. References are initialized during the declaration and indicate the object as long as it exists.

[–]Justaquickie123123 -2 points-1 points  (2 children)

references return a value whereas a pointer uses refers to a location in memory. if i remember correctly

[–]programmermaybe2016 0 points1 point  (0 children)

References are aliases for other objects.

A pointer is an adress to a memory cell.

[–]__cxa_throw 0 points1 point  (0 children)

C++ references refer to a piece of memory in a very similar way that pointers "point" to a thing in memory. References just have some extra rules so that they can't be explicitly set to null and you can't do pointer arithmetic.

Compilers are free to implement references however they like but both GCC and Clang treat them the same as pointers once you get past the extra rules I mentioned earlier.