struct Div
{
int i;
int j;
};
class A
{
public:
A();
Div& divs;
};
In my constructor definition, I have
You should try and initialise your "divs" variable. You cannot have a reference refering to "nothing"...
Have a look here :
http://msdn.microsoft.com/en-us/library/bbt3ewya%28VS.80%29.aspx
Hope this help a bit!
The compiler message is one of those messages that don't make sense from the language point of view, but reveal the inner workings of the compiler, the sequence in which its inner logic works.
In your case you are using an rvalue (NULL
) to initialize a reference. When such initialization is allowed, the rvalue is converted to a temporary object, to which the reference will be bound. So, the compiler has realized it right away and informed you about the fact with a diagnostic message.
In reality though, the trick like that is only allowed for const
references, so your code is broken, since the reference is not const
in our case. Also, a struct
reference, as the one in your code, cannot be initialized with NULL
rvalue (which has integral type), so it is broken for that reason as well.
The compiler's message is rather misleading though. The text of the message seems to imply that it is illegal to initialize member references with temporary objects. In fact, this is legal in C++ (once the above problems are fixed), although it makes no sense. But, I guess, once ill-formed code is accompanied by at least some error message, it should be OK for everyone...
divs is a reference, not a pointer. You can't set it to NULL, it has to point to an actual object of some kind. The best thing to do here is probably to define a static/global instance of Div that you arbitrarily define to be the "Null Div" (set its value to something you're unlikely ever to use) and initialize div to that. Something like this:
struct Div
{
int i;
int j;
};
Div NULL_DIV = { INT_MAX, INT_MAX };
class A
{
public:
A();
Div& divs;
};
A::A() : divs(NULL_DIVS)
{
}
Or, alternatively, just make divs a pointer instead of a reference.
*Note that you can't use a const reference unless you cast away the constness because by default the compiler won't allow you to assign a cosnt ref to a non-const ref.
In "English": a reference refers to something. It cannot refer to nothing (null). That's why references are safer to use then pointers.
Keep in mind that once a reference is initialized to point to something, you cannot alter it to point to something else. If this is not the desired behavior, then you should use a pointer or a copy of the object instead.
I would suggest:
class A{
std::deque<object*>& que = *(std::deque<object*> *)0;
// ...
// Of course `que` is to be assigned valid deque before using it - just like pointers...
};