Gary Wessle wrote:
Quote:
Hi
>
class myType{
public:
void doit();
std::string x;
};
>
int main() {
myType* mt;
mt->doit();
(*mt).x = 4;
}
>
is there a reason why it is better not to use
(*mt).doit();
mt->x = 4;
instead?
>
What is "better" is never, ever access a naked pointer as if it was
actually pointing to something.
The code in main() above:
myType* mt;
mt->doit(); // UB
is undefined behaviour ( should be "dangerous behaviour" (c) ). mt is
an invalid pointer to nothing. A big fat no-no and so nasty its beyond
any description. I strongly suggest you label pointers appropriately
and initialize them to prevent UB.
At least the compiler will generate an error if you attempt to access
an invalid pointer that way.
int main() {
myType* p_mt = 0; // nullptr initialized
myType myinstance;
p_mt = &myinstance; // ah! now we are in business
p_mt->doit();
mt->x = 4;
}
a much better alternative to any of the above is:
int main() {
myType myinstance;
myType& r_mt = myinstance; // a reference
r_mt.doit();
r_mt.x = 4;
}
And perhaps the ptr vs reference semantics might also help you decide
which is better: -for pointers vs . for objects and references.