1

there. I am confused about what the use of the & symbol between the classname and variable name in a c++ #define statement.

I found it in the globalhandling.hpp file in the xbmc source code to create a global singleton.

I wrote a similar version of the snippet to figure out what it does. What I found when experimenting with it is when & is used only one constructor and destructor is called. If I omit it one constructor and two destructors is called.

Is & acting as a bitwise and or an address operator in this context?

#include <iostream>
#include <boost/shared_ptr.hpp>

using namespace std;

class aClass
{
  public:

    aClass() { cout << "Constructor\n"; }


    aClass getInstance() { return *this; }

    void printMessage() { cout << "Hello\n"; }

    ~aClass() { cout << "Destructor\n"; }
};

#define GLOBAL_REF(classname,variable) \
    static boost::shared_ptr<classname> variable##Ref(new classname)

#define GLOBAL(classname,variable) \
    GLOBAL_REF(classname,variable); \
    static classname & variable = (*(variable##Ref.get()))


GLOBAL(aClass,aVariable);

int main()
{   
    aVariable.printMessage();

    return 0;
}
Rakib
  • 7,435
  • 7
  • 29
  • 45

1 Answers1

2

The & symbol you're referring to is presumably this one:

static classname & variable = (*(variable##Ref.get()))

In which case the ampersand isn't anything to do with the C preprocessor, it is in fact the C++ reference symbol.

You would typically use it to refer to an already declared object, similar to a pointer.

For example:

int a = 1;
int b = a;
int &c = a;

// a = 1, b = 1, c = 1.

b = 2;   

// a = 1, b = 2, c = 1.

a = 3;

// a = 3, b = 2, c = 3. Note that variable 'c', which is a reference to 'a', has also changed.

c = 4;

// a = 4, b = 2, c = 4.
Community
  • 1
  • 1
Karl Nicoll
  • 16,090
  • 3
  • 51
  • 65
  • I found out omitting & copies the object rather referencing it. I added a copy constructor to `aClass` to confirm that. – user3625976 May 11 '14 at 17:55