CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 3 123 LastLast
Results 1 to 15 of 33
  1. #1
    George2 is offline Elite Member Power Poster
    Join Date
    Oct 2002
    Posts
    4,468

    Unhappy Reference or pointer, which is better in my case?

    Hi, everyone!


    Sometimes we use pointer as the parameter type and sometimes
    we use reference as the parameter type.

    I think using reference is better than using object directly.
    Since it can save memory and operation (assignment operator).
    But what about pointer V.S. reference? I want to know in which
    case should I use pointer and in which case should I use reference.

    Here are two samples,


    Using reference,

    --------
    ostream& operator << (ostream&, ObjectType);
    --------

    Using pointer
    --------
    MemPoolAddSize (char*, size_t)
    --------


    I want to know your suggestions about pointer v.s. reference.
    What is the general consideration about when using pointer and
    when using reference?


    Thanks in advance,
    George

  2. #2
    Join Date
    Apr 1999
    Location
    Altrincham, England
    Posts
    4,470
    My response is coloured by one simple fact: I hate raw pointers. If I had my way, the entire program would only deal in smart pointers and any naked pointer would be banned.

    So, it should come as no surprise that I favour reference or reference-to-const over pointer or pointer-to-const. If references are inappropriate (because of a heavily heap-based data structure, for example, then my preferred option would be reference-to-smart-pointer. The opportunity for accidentally screwing everything up with raw pointers is just too great for my liking:
    Code:
    // When writing this, the programmer assumed that only heap objects
    // would be passed in...
    void Function(char * ptr)
    {
        // ....
        if (condition)
        {
            delete [] ptr;
            ptr = new char[255];
        }
        // ...
    }
    
    // But later on, someone called it like this:
    
    void Another()
    {
        char str[50];
        strcpy(str, "Hello, world");
        // ...
        Function(str);
    }
    See what I mean?
    Correct is better than fast. Simple is better than complex. Clear is better than cute. Safe is better than insecure.
    --
    Sutter and Alexandrescu, C++ Coding Standards

    Programs must be written for people to read, and only incidentally for machines to execute.

    --
    Harold Abelson and Gerald Jay Sussman

    The cheapest, fastest and most reliable components of a computer system are those that aren't there.
    -- Gordon Bell


  3. #3
    George2 is offline Elite Member Power Poster
    Join Date
    Oct 2002
    Posts
    4,468
    Thanks, Graham buddy!

    I think in your opinion, reference-to-const means
    "const Object&" and pointer-to-const means
    "const Object*". Am I correct?

    But what means "reference or reference-to-const over pointer"?
    What puzzled me most is why a reference is over a pointer?

    Can you show me an example?


    regards,
    George

    Originally posted by Graham
    My response is coloured by one simple fact: I hate raw pointers. If I had my way, the entire program would only deal in smart pointers and any naked pointer would be banned.

    So, it should come as no surprise that I favour reference or reference-to-const over pointer or pointer-to-const. If references are inappropriate (because of a heavily heap-based data structure, for example, then my preferred option would be reference-to-smart-pointer. The opportunity for accidentally screwing everything up with raw pointers is just too great for my liking:
    Code:
    // When writing this, the programmer assumed that only heap objects
    // would be passed in...
    void Function(char * ptr)
    {
        // ....
        if (condition)
        {
            delete [] ptr;
            ptr = new char[255];
        }
        // ...
    }
    
    // But later on, someone called it like this:
    
    void Another()
    {
        char str[50];
        strcpy(str, "Hello, world");
        // ...
        Function(str);
    }
    See what I mean?

  4. #4
    Join Date
    Mar 2003
    Location
    India {Mumbai};
    Posts
    3,871
    I think, you need and mean:

    Code:
    void Function(char  &* ptr);

    and as far as
    Code:
    void Another()
    {
        char str[50];
        strcpy(str, "Hello, world");
        // ...
        Function(str);
    }
    is concerned (in your case) it will do nothing except allocating memory to 'BY VALUE PASSED' pointer. But that would cause error in my (your needed) case.
    Last edited by Ajay Vijay; April 18th, 2003 at 03:46 AM.
    My latest article: Explicating the new C++ standard (C++0x)

    Do rate the posts you find useful.

  5. #5
    Join Date
    Apr 1999
    Location
    Altrincham, England
    Posts
    4,470
    In this context, when I use "over" it's simply for the comparison: it just means that I prefer references to pointers.

    The example is not particularly relevant: my point is that, unless you are very careful (and the authors of any code you use are also very careful) it's extremely easy to completely screw up a program when you start passing raw pointers around. Most importantly, there's the problem of ownership - who is responsible for deleting the pointer? That's the whole purpose of smart pointers - they define ownership, so there's no confusion about who has to free up the memory. Another problem is that there's no (standard) way the you can tell if a pointer points to the heap or to the stack. If it's to the heap, then someone's got to delete it (ownership again); if it points to the stack, then you'd better not delete it or All **** Will Break Loose. Const pointers (e.g. int * const) can help but, let's face it, how often do you see them declared as arguments? No, use references - if you must use a pointer, try to use smart pointer classes to define ownership.
    Correct is better than fast. Simple is better than complex. Clear is better than cute. Safe is better than insecure.
    --
    Sutter and Alexandrescu, C++ Coding Standards

    Programs must be written for people to read, and only incidentally for machines to execute.

    --
    Harold Abelson and Gerald Jay Sussman

    The cheapest, fastest and most reliable components of a computer system are those that aren't there.
    -- Gordon Bell


  6. #6
    George2 is offline Elite Member Power Poster
    Join Date
    Oct 2002
    Posts
    4,468
    Thanks, Graham buddy!

    I think "smart pointer" is a good solution. But I do not
    know what is smart pointer. Can you give me some
    explanations or introduce some online materials for me
    to read?


    regards,
    George

    Originally posted by Graham
    In this context, when I use "over" it's simply for the comparison: it just means that I prefer references to pointers.

    The example is not particularly relevant: my point is that, unless you are very careful (and the authors of any code you use are also very careful) it's extremely easy to completely screw up a program when you start passing raw pointers around. Most importantly, there's the problem of ownership - who is responsible for deleting the pointer? That's the whole purpose of smart pointers - they define ownership, so there's no confusion about who has to free up the memory. Another problem is that there's no (standard) way the you can tell if a pointer points to the heap or to the stack. If it's to the heap, then someone's got to delete it (ownership again); if it points to the stack, then you'd better not delete it or All **** Will Break Loose. Const pointers (e.g. int * const) can help but, let's face it, how often do you see them declared as arguments? No, use references - if you must use a pointer, try to use smart pointer classes to define ownership.

  7. #7
    Join Date
    May 2000
    Location
    Phoenix, AZ [USA]
    Posts
    1,347
    Go to http://www.boost.org.

    Here's the smart pointer area:
    http://www.boost.org/libs/smart_ptr/index.htm

    By the way, auto_ptr is also a smart pointer class; it comes with
    standard C++.

    --Paul

  8. #8
    George2 is offline Elite Member Power Poster
    Join Date
    Oct 2002
    Posts
    4,468
    Thanks PaulWendt buddy!

    I have got it. :-)

    George

    Originally posted by PaulWendt
    Go to http://www.boost.org.

    Here's the smart pointer area:
    http://www.boost.org/libs/smart_ptr/index.htm

    By the way, auto_ptr is also a smart pointer class; it comes with
    standard C++.

    --Paul

  9. #9
    George2 is offline Elite Member Power Poster
    Join Date
    Oct 2002
    Posts
    4,468
    Thanks, Graham buddy!

    I have understood what means "smart pointer". Now I
    have another question. Why do you say "Const pointers
    can help but"? Can you show me an example?


    regards,
    George
    Originally posted by Graham
    In this context, when I use "over" it's simply for the comparison: it just means that I prefer references to pointers.

    The example is not particularly relevant: my point is that, unless you are very careful (and the authors of any code you use are also very careful) it's extremely easy to completely screw up a program when you start passing raw pointers around. Most importantly, there's the problem of ownership - who is responsible for deleting the pointer? That's the whole purpose of smart pointers - they define ownership, so there's no confusion about who has to free up the memory. Another problem is that there's no (standard) way the you can tell if a pointer points to the heap or to the stack. If it's to the heap, then someone's got to delete it (ownership again); if it points to the stack, then you'd better not delete it or All **** Will Break Loose. Const pointers (e.g. int * const) can help but, let's face it, how often do you see them declared as arguments? No, use references - if you must use a pointer, try to use smart pointer classes to define ownership.

  10. #10
    George2 is offline Elite Member Power Poster
    Join Date
    Oct 2002
    Posts
    4,468
    Hi, Graham buddy!

    I have read some materials about smart pointer. And I
    find that it can not be used with standard containers and
    algorithm, since the assignment is not equal.

    Suppose you put smart pointer into a vector and than
    use sort to ...

    BTW: is smart pointer widely used yet?


    regards,
    George

    Originally posted by Graham
    In this context, when I use "over" it's simply for the comparison: it just means that I prefer references to pointers.

    The example is not particularly relevant: my point is that, unless you are very careful (and the authors of any code you use are also very careful) it's extremely easy to completely screw up a program when you start passing raw pointers around. Most importantly, there's the problem of ownership - who is responsible for deleting the pointer? That's the whole purpose of smart pointers - they define ownership, so there's no confusion about who has to free up the memory. Another problem is that there's no (standard) way the you can tell if a pointer points to the heap or to the stack. If it's to the heap, then someone's got to delete it (ownership again); if it points to the stack, then you'd better not delete it or All **** Will Break Loose. Const pointers (e.g. int * const) can help but, let's face it, how often do you see them declared as arguments? No, use references - if you must use a pointer, try to use smart pointer classes to define ownership.

  11. #11
    Join Date
    Apr 1999
    Location
    Altrincham, England
    Posts
    4,470
    You've been reading about auto_ptr. That is, as you've said, not usable in standard containers because it transfers ownership on copying. The smart pointers I'm referring to don't exist in the standard library. Try looking up the boost smart pointers for an alternative that will work with the STL containers.
    Correct is better than fast. Simple is better than complex. Clear is better than cute. Safe is better than insecure.
    --
    Sutter and Alexandrescu, C++ Coding Standards

    Programs must be written for people to read, and only incidentally for machines to execute.

    --
    Harold Abelson and Gerald Jay Sussman

    The cheapest, fastest and most reliable components of a computer system are those that aren't there.
    -- Gordon Bell


  12. #12
    George2 is offline Elite Member Power Poster
    Join Date
    Oct 2002
    Posts
    4,468

    Unhappy

    Thanks, Graham buddy!

    The materials is helpful. I have another question about
    your reply. As you said, another solution is using const
    pointers. But I have tried the following example. I see
    we can still delete const pointers at anywhere we can.
    So I think const pointer can not define ownership and
    it still can not say by itself whether it is pointed to a heap
    or a stack. Why you say before that const pointer can
    resolve the trouble? Can you show me an example? Such
    is my example which shows const pointer can not help out.
    What is wrong with my code and idea?

    Sample code:

    --------
    #include <iostream>

    using namespace std;

    int main()
    {
    int j = 100;
    int * const p = new int;
    *p = j;

    //we can still delete it here
    delete p;
    return 1;
    }
    --------


    have a nice weekend,
    George
    Originally posted by Graham
    You've been reading about auto_ptr. That is, as you've said, not usable in standard containers because it transfers ownership on copying. The smart pointers I'm referring to don't exist in the standard library. Try looking up the boost smart pointers for an alternative that will work with the STL containers.

  13. #13
    George2 is offline Elite Member Power Poster
    Join Date
    Oct 2002
    Posts
    4,468
    Hi, Graham buddy!

    I have referenced a rule from Scott Meyers's in which
    case shoule we use pointer instead of reference, that is
    if you want to allow for a non-existing reference (NULL), use a pointer.


    Thanks in adavnce,
    George

    Originally posted by Graham
    You've been reading about auto_ptr. That is, as you've said, not usable in standard containers because it transfers ownership on copying. The smart pointers I'm referring to don't exist in the standard library. Try looking up the boost smart pointers for an alternative that will work with the STL containers.

  14. #14
    Join Date
    Apr 2003
    Location
    Morelia, Mexico
    Posts
    40
    my choice are pointers, all the times.

    even "this" is a pointer
    int i;main(){for(;i["]<i;++i){--i;}"];read('-'-'-',i+++"hell\
    o, world!\n",'/'/'/'));}read(j,i,p){write(j/p+p,i---j,i/i);}

  15. #15
    Join Date
    Apr 1999
    Location
    Altrincham, England
    Posts
    4,470
    Why you say before that const pointer can
    resolve the trouble?
    I said that const pointers can help, not resolve. Nor did I say that const pointers can define ownership. A const pointer can't be reseated (made to point somewhere else), so there's one potential trouble area gone. But, of course, they can be deleted (it would be a bit pointless if they couldn't), so that problem area remains. And they still don't define ownership.
    I have referenced a rule from Scott Meyers's in which
    case shoule we use pointer instead of reference, that is
    if you want to allow for a non-existing reference (NULL), use a pointer.
    YES! and wrap the (pointer) argument in a bl**dy smart pointer class! Look, I pride myself on having quite a considerable degree of patience, but this is getting ridiculous. You keep coming up with things that you ought to be able to resolve yourself with just a few moment's thought. It's not difficult. If you've been reading Scott Meyers, then you should also have read the sections in his books about smart pointers, their usefulness and how to use them.
    my choice are pointers, all the times.

    even "this" is a pointer
    Whoopee-dee. Now would you care to elaborate and give a reasoned argument why? So what if this is a pointer? What difference does that make? this is a special case - for one thing, it's a const pointer (see above). For another, its usage is entirely different to other pointers, so it doesn't suffer from the same failings. I am interested to know how you prevent accidental misuse of pointers in your program, and what measures you take to avoid memory leaks.
    Correct is better than fast. Simple is better than complex. Clear is better than cute. Safe is better than insecure.
    --
    Sutter and Alexandrescu, C++ Coding Standards

    Programs must be written for people to read, and only incidentally for machines to execute.

    --
    Harold Abelson and Gerald Jay Sussman

    The cheapest, fastest and most reliable components of a computer system are those that aren't there.
    -- Gordon Bell


Page 1 of 3 123 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured