"John Carson" <jc****************@netspace.net.au> writes:
"Stein Gulbrandsen" <sg*****@online.no> wrote in message
news:43******@news.broadpark.no Is this legal C++?
or am I dereferencing posssibly invalid addresses here?
c = &a[0];
Illegal. a contains random junk; it does not point to valid memory.
... std::vector<C> v;
c = &*v.begin();
Likewise illegal. v.begin() doesn't point to anything valid so you shouldn't
dereference it.
... C& r = v.front();
Illegal.
Thanks, that is what I would also think. So, if I understand things
right, all the 8 numbered lines below are illegal (undefined
behaviour). Nevertheless, it compiles silently (except for Sun
compiler warning about the reference to non-const at 8) and runs "OK"
(producing 8 zeroes on cout) on Sun WS C++, SGI Mipspro C++, Microsoft
Visual C++/.net, and g++.
It seems that no dereferencing is actually taking place.
Is this just by chance, because of some implementation details of the
compilers, or are any of these lines actuallly legal C++?
#include <vector>
#include <iostream>
class C{}; C* c = 0; // C is defined
class D; D* d = 0; // D is not defined
std::vector<int> v; // empty
int main () {
D& r = *d; // 1a
std::cout << &r << " " // 1b
<< &*static_cast<D*>(0) << " " // 2
<< &*d << " " // 3
<< &c[0] << " " // 4
<< &0[static_cast<C*>(0)] << " "// 5
<< &v[0] << " " // 6
<< &*v.begin() << " " // 7
<< &std::vector<C>().front() // 8
<< "\n";
}
--
stein