在我工作的地方我看到这种风格广泛使用: -参考成员变量的类成员
#include <iostream>
using namespace std;
class A
{
public:
A(int& thing) : m_thing(thing) {}
void printit() { cout << m_thing << endl; }
protected:
const int& m_thing; //usually would be more complex object
};
int main(int argc, char* argv[])
{
int myint = 5;
A myA(myint);
myA.printit();
return 0;
}
是否有来形容这个成语的名称?我假设它是为了防止复制大型复杂对象的可能的大开销?
这是一个很好的做法吗?这种方法有没有陷阱?
如果您在成员变量中引用的对象在别处销毁并尝试通过类访问它,则可能出现的一个错误 – mathematician1975