86

There seems to be many relavent questions talking about pointer vs. reference, but I couldn't find what I want to know. Basically, an object is passed in by a reference:

funcA(MyObject &objRef) { ... }

Within the function, can I get a pointer to that object instead of the reference? If I treat the reference objRef as an alias to the MyObject, would &objRef actually give me a pointer to the MyObject? It doesn't seem likely. I am confused.

Edit: Upon closer examination, objRef does give me back the pointer to object that I need - Most of you gave me correct info/answer, many thanks. I went along the answer that seems to be most illustrative in this case.

6
  • 1
    Why do you need a pointer from a reference?
    – Griwes
    Feb 13, 2012 at 16:02
  • 3
    @Griwes: Off the top of my head, pointer math may be desired or another API may want a pointer. Feb 13, 2012 at 16:05
  • 1
    what if you just get the address of the reference? &objRef
    – vulkanino
    Feb 13, 2012 at 16:06
  • @DrewDormann, what, pointer math on address of object passed by reference? Doesn't look like good design to me.
    – Griwes
    Feb 13, 2012 at 16:06
  • 4
    An example would be a reference is passed in, the parsing of binary stream such as reinterpret_cast<char *> requires a pointer type instead.
    – Oliver
    Feb 13, 2012 at 16:12

6 Answers 6

136

Yes, applying the address-of operator to the reference is the same as taking the address of the original object.

#include <iostream>

struct foo {};

void bar( const foo& obj )
{
  std::cout << &obj << std::endl;
}

int main()
{
  foo obj;
  std::cout << &obj << std::endl;
  bar( obj );

  return 0;
}

Result:

0x22ff1f
0x22ff1f
0
45

Any operator applied to a reference will actually apply to the object it refers to (§5/5 [expr]); the reference can be thought of as another name for the same object. Taking the address of a reference will therefore give you the address of the object that it refers to.

It as actually unspecified whether or not a reference requires storage (§8.3.2/4 [dcl.ref]) and so it wouldn't make sense to take the address of the reference itself.

As an example:

int x = 5;
int& y = x;
int* xp = &x;
int* yp = &y;

In the above example, xp and yp are equal - that is, the expression xp == yp evaluates to true because they both point to the same object.

30
  • 8
    The reference is NOT simply another name for the same object (the lifetime of a reference is distinct from the lifetime of the object it points to). However, your sample code will work, because using any operator on a reference actually uses the target object instead.
    – Ben Voigt
    Feb 13, 2012 at 16:13
  • 1
    @Loki: What? A reference can definitely "not live as long as the object", and it can also outlive the object. Using a reference after the lifetime of its original target object has ended is undefined behavior under all but very specific and restricted conditions.
    – Ben Voigt
    Feb 13, 2012 at 16:53
  • 3
    @Ben: Yes I always found one sided arguments (blogs) are the greatest way to get to the truth. You said it yourself a reference is an alias. Alias => 'Another Name'. Yes. perfectly legal code can still lead to undefined behavior. What I am saying is valid code (ie that does not invoke undefined behavior) a reference will not last longer than an object it refers too and acts as another name for an object. You are saying: A reference behaves like a pointer when we invoke undefined behavior. I say yep, so what. Feb 14, 2012 at 15:25
  • 2
    @Loki: I'm replacing an int with another int in the exact same location, no problems there. And clearly it's a new object (destructor ran on the old one, constructor ran for the new one). The standard also says it's a new object. I can't see that your new-found approach to this (replacing the now-defeated claim of undefined behavior) makes any sense at all, since it completely removes any meaning of the term "object lifetime". Seems more like an desperate attempt to excuse your repeated attacks on my comment and example.
    – Ben Voigt
    Feb 14, 2012 at 16:33
  • 2
    Agreed. For anyone that encounters this in the future, and gets curious, I'd just like to point out that § 3.8.1 ([basic.life]/1) explicitly states that for an object of type T, its lifetime begins when "storage with the proper alignment and size for type T is obtained, and if the object has non-trivial initialization, its initialization is complete.", and that its lifetime ends when "if T is a class type with a non-trivial destructor (12.4), the destructor call starts, or the storage which the object occupies is reused or released." (According to the C++14 standard.) Nov 21, 2016 at 0:07
29

The general solution is to use std::addressof, as in:

#include <type_traits>

void foo(T & x)
{
    T * p = std::addressof(x);
}

This works no matter whether T overloads operator& or not.

1
  • 2
    Excellent point, since the reference is the referred object, one needs to be careful if said object might overload operator &... rare but invaluable for proxy classes... one day I'll resume that project where I needed this! Apr 11, 2016 at 22:53
8

Use the address-of (&) operator on the reference.

&objRef

Like any other operator used on a reference, this actually affects the referred-to object.

As @Kerrek points out, since the operator affects the referred-to object, if that object has an overloaded operator& function, this will call it instead and std::address_of is needed to get the true address.

8

Use the address operator on the reference.

MyObject *ptr = &objRef;
2
  • This doesn't get "the address of the reference".
    – Ben Voigt
    Feb 13, 2012 at 16:17
  • @BenVoigt: Would "Use the address operator on the reference" be more accurate? I get that you don't like my terminology, but I want to be sure why. Feb 13, 2012 at 16:45
-3

In C++, a reference is a restricted type of pointer. It can only be assigned once and can never have a NULL value. References are most useful when used to indicate that a parameter to a function is being Passed by Reference where the address of the variable is passed in. Without a Reference, Pass By Value is used instead.

6
  • No. A reference is an alias to an existing object. Thinking of it as a fancy pointer will just confuse you when you start doing more complex stuff. Feb 13, 2012 at 16:13
  • @Loki: A reference is a handle. So is a pointer. Both of them consume storage (unless optimized away) and have distinct lifetime from the referred-to object. The similarities greatly outweigh the differences.
    – Ben Voigt
    Feb 13, 2012 at 16:16
  • @BenVoigt: Careful on terminology. Handle has other meanings in comp sci. But I take your point. But I disagree with your opinion. Also note 8.3.2 References [dcl.ref] para 4 <quote>it is unspecified whether or not a reference requires storage</quote> If a reference is like a pointer why can't I get a reference to my reference (its because it does not exist). It is simply an alias. Feb 13, 2012 at 16:36
  • @damson: Yes there a lots of crap references on the web. Pick up a copy of the standard here: stackoverflow.com/a/4653479/14065 Feb 13, 2012 at 16:39
  • Just look at this: reference to know what is the comportment of a reference and this: pointers cause your don't know what is a pointer.
    – damson
    Feb 13, 2012 at 16:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.