Re: trouble assigning reference
On May 7, 8:47 am, Christopher <cp...@austin.rr.com> wrote:
Two more questions though:
1) I think I can have a null reference.
No. The C++ standard clearly says that "null reference cannot exist in
a well-defined program" (8.3.2p4)
Note that a reference can never be null, it can refer to a pointer
that can be null.
What can i expect when this
happens:
#include <iostream>
int main()
{
int * ptr = new int(7);
int & ref = *ptr;
delete ptr;
// more stuff
std::cout << ref << std::endl;
}
This is an undefined behaviour, since you are trying to dereference
the pointer ptr after deleting it.
2) Is this safe?
#include <iostream>
class A
{
public:
A() { m_ptr = new int(9); }
~A() { delete m_ptr; }
const int & GetInt() const { return *m_ptr; }
private:
int * m_ptr;
};
int main()
{
A a();
Beware - You think you are defining an object of type A using the 0-
arg constructor, but the compiler thinks something totally different.
The compiler treats this as a function declaraction for a function a
that takes nothing and returns a.
If you want to declare a variable representing an object of type a,
simply say
A a;
int * anotherPtr = &(a.GetInt());
This line gives error since a is a treated as a function by the
compiler and there is no way it can have GetInt member function.
Changing A a() to A a will remove this error, but still there is one
more error. Observe that GetInt function returns a reference to a
const-int. Hence, &(a.GetInt()) has type "pointer-to-const". A pointer-
to-const cannot be assigned to a pointer-to-non-const. You will need
to change int * anotherPtr to const int* anotherPtr to make this line
compile.
std::cout << *anotherPtr << std::endl;
return 0;
}
Finally, it is OK to have anotherPtr as long as you donot delete
anotherPtr or try to dereference it after the object "a" ceases to
exist. But this kind of usage might unknowingly lead you in trouble,
specifically if you aren't sure what all places is this pointer being
used.
Thanks.