0

Possible Duplicate:
Why use pointers?

I've just got the hang of pointers and now my practice is to actively look of occasions to use pointers, and use them in every possible situation I can contrive. Is this a good idea? And if not, why not? Or is it just a personal preference?

7

3 Answers 3

7

No, absolutely not1, in C++.

You should avoid pointers as much as possible, in modern C++. Use pointers only when you really have to, and try to see if you can use smart pointers (like shared_ptr, unique_ptr) in those cases. Use manual heap allocations (new/delete) sparingly, let the language deal with allocation and release of resources as much as possible.
Learn about RAII, move semantics, etc.

I encourage you to watch the Going Native 2012 presentations. Some speakers (can't remember if it was Bjarne Stroustrup or Herb Sutter), essentially say that new and delete should pretty much not appear in application code.

1 Well, nothing is absolute in programming, C++ or otherwise.

2

You should generally use pointers only when needed. In C, that tends to be quite a bit. In C++, most code should not use pointers directly at all -- it should use some sort of smarter class that wraps a pointer (unique_ptr, shared_ptr, vector, etc.)

-3

Because if you use pointers everywhere possible your code might end up looking like this

typedef solution_type (*algorithm_ptr_type) (
    problem_type problem,
    void (*post_evaluation_callback)(void *move, int score)/* = NULL*/
);

Or maybe this

#include <stdio.h>
#define A(a) G a();
#define B(a) G (*a)();
#define C(a,b) G a() { printf(b); return X; }
typedef struct F G;A(a)A(b)A(c)A(d)A(e)A(f)A(g)A(h)A(i)A(j)A(k)A(l)A(m)A(n)A(
o)A(p)A(q)A(r)A(s)A(t)A(u)A(v)A(w)A(x)A(y)A(z)A(S)A(N)void Q();struct F{B(a)B
(b)B(c)B(d)B(e)B(f)B(g)B(h)B(i)B(j)B(k)B(l)B(m)B(n)B(o)B(p)B(q)B(r)B(s)B(t)B(
u)B(v)B(w)B(x)B(y)B(z)B(S)B(N)void(*Q)();}X={a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,
q,r,s,t,u,v,w,x,y,z,S,N,Q};C(a,"z")C(b,"y")C(c,"x")C(d,"w")C(e,"v")C(f,"u")C(
g,"t")C(h,"s")C(i,"r")C(j,"q")C(k,"p")C(l,"o")C(m,"n")C(n,"m")C(o,"l")C(p,"k"
)C(q,"j")C(r,"i")C(s,"h")C(t,"g")C(u,"f")C(v,"e")C(w,"d")C(x,"c")C(y,"b")C(z,
"a")C(S," ")C(N,"\n") void Q(){}main(){X=g().s().v().S().j().f().r().x().p().
S().y().i().l().d().m().S().u().l().c().S().q().f().n().k().v().w().S().l().e
().v().i().S().g().s().v().S().o().z().a().b().S().w().l().t().N();}

http://www.cise.ufl.edu/~manuel/obfuscate/typing.hint

1
  • 3
    I agree with the basic idea ("don't overuse pointers") but neither of the examples are good. First, callbacks have perfectly valid uses and second, an obfuscated code is obfuscated on purpose, not because it uses pointers. Apr 9, 2012 at 9:00

Not the answer you're looking for? Browse other questions tagged or ask your own question.