Connecting Tech Pros Worldwide Help | Site Map

de-reference a pointer to object

Gary Wessle
Guest
 
Posts: n/a
#1: Dec 7 '06
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?

thanks



Ivan Novick
Guest
 
Posts: n/a
#2: Dec 7 '06

re: de-reference a pointer to object


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?
Why would you bother dereferencing the pointer and then using dot
operator instead of just using the pointer notation - ?

There should be no noticable difference in the effect of the two
statements but the pointer notation is more clear.

-
Ivan
http://www.0x4849..net

red floyd
Guest
 
Posts: n/a
#3: Dec 7 '06

re: de-reference a pointer to object


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?
>
thanks
>
To me, mt->whatever reads better. I tend to read it as "mt pointing at
whatever", making it clear that mt is a pointer (or pointer-like object).

But don't mix the two notations. It leads to confusion. Either stick
with (*mt).whatever everywhere or go with mt->whatever. You'll find
that most people us the second notation.


Salt_Peter
Guest
 
Posts: n/a
#4: Dec 7 '06

re: de-reference a pointer to object



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.

Closed Thread