[英]& symbol in C++ preprocessor
there. 那里。 I am confused about what the use of the & symbol between the classname and variable name in a c++ #define statement.
我对C ++ #define语句中的类名和变量名之间的&符号的用法感到困惑。
I found it in the globalhandling.hpp file in the xbmc source code to create a global singleton. 我在xbmc源代码的globalhandling.hpp文件中找到了它,以创建一个全局单例。
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;
}
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 . 在这种情况下,&符与C预处理器无关,实际上是C ++ 参考符号 。
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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.