-3

I created a member function that returning reference to object.

I can do it like:

class Foo {
  Foo &ref(){
    return *this;
  }
}

ref returning object by look up this pointer.

Is there any way else to return object without using this?

EXPLAIN the reason:

The reason I don't want to use this is: the pointer occupy 4B in stack whereas the reference share the same memory

DMaster
  • 603
  • 1
  • 10
  • 23

1 Answers1

1

It sounds like you don't like this and you don't want to dereference any pointers. How about:

class Foo {
  private:
    int dummy;
  public:
    Foo& ref() {
        return reinterpret_cast<Foo&>(dummy);
    }
};
static_assert(std::is_standard_layout<Foo>::value,
              "Foo must be standard-layout!");

Because Foo is a standard-layout class and dummy is its first non-static data member and there are no base classes, the address of dummy is the same as that of the containing Foo.

Needless to say, this is a very silly way to return a reference to an object and I can't see any possible justification for doing it this way. Not wanting to write return *this; is like wanting to add two integers without using +. It just makes no sense at all.

Brian Bi
  • 111,498
  • 10
  • 176
  • 312
  • anyway, thank you. The reason I don't want to use `this` is: the pointer occupy 4B in stack whereas the reference share the same memory – DMaster May 08 '15 at 07:38
  • 2
    @DMaster That's simply not right. The generated machine code will usually have to store the address of a reference somewhere like it stores a pointer's value. In some cases a reference can be optimized out, but the same is true for pointers. – Brian Bi May 08 '15 at 07:48
  • @DMaster You can find questions like that on this site, e.g., http://stackoverflow.com/questions/7058339/c-when-to-use-references-vs-pointers – Brian Bi May 08 '15 at 22:21