1

I'm following a D2D sample and therein, this code came up:

    if(!(D2D1_WINDOW_STATE_OCCLUDED & m_renderTarget->CheckWindowState()))
    {
        m_renderTarget->BeginDraw();

        Draw();

        if(m_renderTarget->EndDraw() == D2DERR_RECREATE_TARGET)
        {
            m_renderTarget.Reset();
            Invalidate();
        }
    }

I noticed that the m_renderTarget used both the -> (I forget what it's called) and later uses the dot operator. For some reason I thought that use could only use one or the other depending of if it was a reference type or value type. Apparently I thought wrong but can't find any information about when to use each operator (or more to the point, the purpose of each operator.)

Any clarification would be greatly appreciated.

Nate222
  • 856
  • 2
  • 15
  • 25

2 Answers2

6

I thought that use could only use one or the other depending of if it was a reference type or value type

Usually, yes.

The fact that both are used on the same object in your code indicates it is a "smart pointer" i.e. an object type which has an overloaded operator-> that allows it to act like a pointer.

    m_renderTarget->BeginDraw();

This uses the operator-> to access a member of the object it points to. BeginDraw is a member function of the pointed-to object, not of m_renderTarget.

    m_renderTarget.Reset();

This accesses a member of m_renderTarget itself, not the object it points to. Typically a reset() member replaces the pointed-to object with a null pointer.

So in the first case the -> syntax does something with the object it points to, and in the second case the . syntax does something to the object itself.

Jonathan Wakely
  • 166,810
  • 27
  • 341
  • 521
-1

What the arrow operator does is deference a pointer(pointing towards an object) and then use the ‘ . ‘ operator on the leftover expression.

Its same as

    (*m_renderTarget).BeginDraw();

Arrow operator is used to avoid confusion with this

    *(m_renderTarget.BeginDraw());

which of course could be disastrous and could cause program crashes.

This explained with a good example here

DotNetUser
  • 6,494
  • 1
  • 25
  • 27