Click to See Complete Forum and Search --> : Reference or pointer, which is better in my case?


George2
April 17th, 2003, 09:52 AM
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

Graham
April 17th, 2003, 10:54 AM
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:

// 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?

George2
April 17th, 2003, 08:43 PM
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:

// 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?

Ajay Vijay
April 18th, 2003, 03:41 AM
I think, you need and mean:

void Function(char &* ptr);
:D :D :D
and as far as
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.

Graham
April 18th, 2003, 05:14 AM
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.

George2
April 18th, 2003, 06:23 AM
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.

PaulWendt
April 18th, 2003, 07:26 AM
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

George2
April 18th, 2003, 07:40 AM
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

George2
April 18th, 2003, 07:42 AM
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.

George2
April 18th, 2003, 11:35 PM
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.

Graham
April 19th, 2003, 05:39 AM
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 (http://www.boost.org/libs/smart_ptr/smart_ptr.htm) for an alternative that will work with the STL containers.

George2
April 19th, 2003, 09:18 AM
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 (http://www.boost.org/libs/smart_ptr/smart_ptr.htm) for an alternative that will work with the STL containers.

George2
April 19th, 2003, 09:24 AM
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 (http://www.boost.org/libs/smart_ptr/smart_ptr.htm) for an alternative that will work with the STL containers.

Luis G
April 19th, 2003, 12:20 PM
my choice are pointers, all the times.

even "this" is a pointer ;)

Graham
April 19th, 2003, 02:45 PM
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.

Luis G
April 19th, 2003, 05:21 PM
Originally posted by Graham

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.

Sorry for just voicing my opinion, without some back up. Also, by saying that this is a pointer i was just being ironic :)

I don't diminish references, i just don't like them, when managing a lot of variables in a function, i prefer to have the certainty of *ptr within a function just to make sure it is an external value. Thus this will only apply to passing arguments by reference. As it won't make a real difference to me to use a reference if the arguments are not going to be modified, i just feel more comfortably using pointers to do such task as well.

But to answer your question about the things i do to avoid misuse of my pointers all i have to say is: i design the code first, i'm not the type of guy that just starts writing code, i do design and make some crazy drawings that only i can understand. Is not big deal to use the riskiest stuff of C as long as you do it properly, and you analize even the most remote possibility of taking the system to a not desired state.

Here are some of things i do when using pointers:
- I like pointers, but i don't like to use pointer arithmetic, i rather use the array form, clearer and less vulnerable to coding errors.
- I don't do stuff like ptr=&a[s], i rather use another index for the array.
- All pointers are initialized to NULL when i declare them, and are set back to NULL after a free() call.
- Each function is encapsulated enough to do its job independently of the others, thus it should check wether the pointer is NULL or not and take actions accordingly (they usually do a return -1; in my coding style).
- When i'm allocating memory to a pointer, i make sure to have the keep the number of elements stored in the dynamic array in a variable or via a #define; if the size varies from very small to very big, i implement a list.


I programmed very tricky data structures for my OS II class, something like a list of lists of lists with several pointers in each of the "last list" nodes, it didn't fail, and the memory managment went by flawlessly and completely transparent to the other portion of the code.

galathaea
April 19th, 2003, 06:29 PM
Originally posted by Luis G
- All pointers are initialized to NULL when i declare them, and are set back to NULL after a free() call.
- Each function is encapsulated enough to do its job independently of the others, thus it should check wether the pointer is NULL or not and take actions accordingly (they usually do a return -1; in my coding style).
- When i'm allocating memory to a pointer, i make sure to have the keep the number of elements stored in the dynamic array in a variable or via a #define; if the size varies from very small to very big, i implement a list.
So you are a strongly c-styled programmer (free???)...
But to answer your question about the things i do to avoid misuse of my pointers all i have to say is: i design the code first, i'm not the type of guy that just starts writing code, i do design and make some crazy drawings that only i can understand. Is not big deal to use the riskiest stuff of C as long as you do it properly, and you analize even the most remote possibility of taking the system to a not desired state.
...who doesn't work with others. So of course program with pointers! C doesn't have references, so you probably don't have much familiarity with them, and you will want to program in the way that you are most familiar with since you have no one to answer to. That way, your programs will be as bug-free as possible.

But when teaching c++, these kind of things should be taught differently than the c style approach, because c++ is a different language than c. In c++, it is best to use vectors over arrays. In c++, we encapsulate with objects and namespaces, not functions and linkage specifiers. And in c++, it really is best to avoid naked pointers if at all possible. This is all part of the different way that the dominant c++ paradigms view programming compared with dominant c paradigms. The whole raison d'etre for c++ is that we can manage related actions in object-oriented pieces to seriously reduce the chance for error and indeed reuse code for quicker development, and this includes pointers and lifetime management, array indexing, etc.

Originally posted by George2
BTW: is smart pointer widely used yet?
Yes, most definitely. There are in fact some lucky students who get taught to use them before diving in to the more low level pointer management issues.

Luis G
April 19th, 2003, 09:23 PM
I'm also very familiar with the OOP paradigm, and i also do some coding in C++, it's just that i pick up what's best of both languages, i can say that most of my code is actually done in C/C++, i can write in pure C++ thou.

btw, malloc() is to new just as free() is to delete ;)

George2
April 19th, 2003, 11:26 PM
Thanks, Graham buddy!

George

Originally posted by Graham

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.

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.

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.

Paul McKenzie
April 20th, 2003, 01:18 AM
Originally posted by Luis G
I'm also very familiar with the OOP paradigm, and i also do some coding in C++, it's just that i pick up what's best of both languagesWhich sounds dangerous to me. You either program in C or C++. i can say that most of my code is actually done in C/C++There is no such language as C/C++, It's either 'C' or C++.
btw, malloc() is to new just as free() is to delete ;) No they are not.

a) malloc() and free() are 'C' heap functions. new, delete, new[], delete[] are operators that manipulate the free store.

b) new / delete create objects by calling the constructor / destructor. malloc() and free() do not have such facilities.

c) Since new / delete are operators, they can be overloaded.

Also, I saw the list of 'C' things you do in your programs. I have to agree with galathaea and Graham -- you can eliminate a lot of your problems by using C++ techniques, and not rely on 'C' to solve your problems. For example, you mention dynamic arrays -- are you using vector<T> to accomplish this? If not, why? Why maintain #defines when this is all taken care of by the standard library container classes?

The problem that I have is that a lot of 'C' programmers who use C++ always (and I've stated this before in this group) take the path of least resistance -- and that is to resort to 'C' instead of using (i.e. learning) proper C++ ways to solve a problem. The problem with this is that the 'C' approach not only is harder to maintain, but in some cases will not work or will lead to undefined behavior if applied in a C++ program. For example, memcpy()ing a non-POD structure, using qsort() on non-POD data types, the usage of strcpy(), strcat(), etc when std::string should be used, etc. It almost seems like the 'C' programmer who use C++ feel slighted when they find that a lot the 'C' code they've written can be tossed, so they fight the losing battle by insisting that their old 'C' code is "great", "more efficient", etc. than what the standard library provides. Basically, the problem is that the 'C' programmer has to "unlearn" a lot of what they were taught when they switch to programming in C++.

Maybe you should get the book "Accelerated C++" by Koenig and Moo. This book is made for programmers who are already experienced in another language who are starting out in C++. The book introduces you to std::string, std::vector, std::list, etc. way before anything is discussed about new[] and delete[] to create dynamic arrays. This is the way that C++ should be taught, but unfortunately in almost all classrooms, the C++ courses are nothing more than C programming courses with a couple of notes on virtual and overloaded functions.

Regards,

Paul McKenzie

Ajay Vijay
April 20th, 2003, 03:49 AM
Absolutely fine article!! I appreciate it deeply!!

Paul McKenzie
April 20th, 2003, 08:23 AM
Originally posted by Luis G
I programmed very tricky data structures for my OS II class, something like a list of lists of lists with several pointers in each of the "last list" nodes, it didn't fail, and the memory managment went by flawlessly and completely transparent to the other portion of the code. You mean you did this:

#include <list>
typedef std::list<std::list<double> > ListInList;
A list of a list of doubles. No "tricky" pointers, no code to debug, nothing. All I need is to know how to use the std::list public interface. This is the major difference in C and C++ coding. You (or someone else in the future) would have to maintain your "tricky" linked list program, leading to potential bugs and maintenance issues if something needs to be added or changed. There is no code maintenance needed for the definition I provided above -- the only thing necessary is that the programmer be competent in the standard C++ classes.

Regardless of how competent you feel you are with pointers, you will not be infallible. This is explained quite well in the C++ FAQ here in section 34.1:

http://www.parashift.com/c++-faq-lite/containers-and-templates.html

Regards,

Paul McKenzie

Luis G
April 20th, 2003, 12:24 PM
woah, bash the C programmer ;)

Paul McKenzie, i know the differences between memory allocation in C and C++, but still they are equivalent for their respective language :rolleyes:, i never stated that C/C++ is a language, i said that most of my code is done in C/C++ or "a mixture of C and C++" is that so hard to understand?.

I completely agree with you, C programmers are resistant to C++ mainly because C++ also includes the C language, something that should not have happened in the first place. Plus, if we add a line that's very hard to define between the two paradigms, because there's no "completely oop programing" you will always end up doing some structured coding, mainly in the class methods.

I took one semester of C, and then another semester of C++, when i learnt C++ i'm possitive that it wasn't a "C programming course with a couple of notes on virtual and overloaded functions.", starting with the oop paradigm and its history before actually learning the coding in C++.

Thanks for the book recommendation, i might read it later. Guess is time to remove the dust out of some of my oop books, i knew there were some advantages in C++ over C, i never took the time to learn them all, 'cause by the only time i programmed in pure oop was for my project of my C++ course. After that i went back to old-style C coding.

No code is infallible, not even the one you get from the standard C++ classes. Many bugs are introduced on the compiler behalf and some others are in the classes themselves. Not that i'm excusing myself for trying to do it manually and i understand the risks of someone else managing my code (proper software engineering and documentation should help on that thou), just pointing out that there's no perfect code.

Paul McKenzie
April 20th, 2003, 07:33 PM
Originally posted by Luis G I took one semester of C, and then another semester of C++, when i learnt C++ i'm possitive that it wasn't a "C programming course with a couple of notes on virtual and overloaded functions."Did you discuss, usage of vector<> instead of hand-coded dynamic arrays? How about usage of std::string instead of the "new char [x] / delete []" stuff?. Was it close to what Stroustrup describes in his paper?

http://www.research.att.com/~bs/new_learning.pdf

The dead giveaway is if 'C' programming was a prerequisite to the C++ course. If 'C' programming was a prerequisite to C++, then that shows where the problem was -- it presumed that you need to know C before learning C++ -- absolute nonsense. As a matter of fact, it makes the job harder in converting 'C' minds into C++ minds, as the FAQ I posted a link to describes.
Thanks for the book recommendation, i might read it later. It is the best book made for experienced programmers when they want to learn C++, IMO and in the opinion of almost every C++ expert.Guess is time to remove the dust out of some of my oop books,You mention OOP, but what you are talking about is not necessarily OOP, but basic C++ programming principles. Another paper by Stroustrup describes this problem with describing things as OOP.

http://www.research.att.com/~bs/oopsla.pdf

i knew there were some advantages in C++ over CThe C++ course you took should have emphasized this. i never took the time to learn them all, 'cause by the only time i programmed in pure oop was for my project of my C++ course. After that i went back to old-style C coding.Why? after seeing what vector<> or list<> does, I wouldn't even think about writing a dynamic array class or to write my own linked list class (again, this should have been emphasized by the course you took -- it isn't all about OOP).No code is infallible, not even the one you get from the standard C++ classes.Neither is the code from the 'C' library, such as strcpy() and memcpy(). How do you know that the memcmp() or memmove(), or malloc() has been fully debugged? The 'C' programmer never hesitates in using these funtions. The same way a 'C' programmer uses the 'C' library without a second-thought as to whether there are bugs is the same way a C++ programmer uses the C++ standard library.
Many bugs are introduced on the compiler behalf and some others are in the classes themselves.How many bugs have you found? I use the library all the time, and it will be really difficult to find bugs in the library. Just like it would be very hard for me to find bugs in the 'C' library.
just pointing out that there's no perfect code. The standard library classes have been written by some of the best C++ programmers in the business, if not the world. Myself and other C++ programmers will use it to make our programming more robust, more bug-free, with less maintenance headaches and costs.

BTW, "The C++ Standard Library" by Nicolai Josuttis, should be on every C++ programmer's bookshelf.

Regards,

Paul McKenzie

PaulWendt
April 20th, 2003, 09:32 PM
Originally posted by Paul McKenzie
BTW, "The C++ Standard Library" by Nicolai Josuttis, should be on every C++ programmer's bookshelf.

Regards,

Paul McKenzie

Not to step all over Paul's posts or anything, but I bought this
book on his advice. I must strongly agree with his statement.
The book is an excellent reference manual in my opinion and
helps to teach the proper way of using the standard library. It
also helps to point out some pitfalls and common misconceptions
that a lot of people [like me] might have.

Paul also recommended the Scott Meyers series of books and I
read those as well. They are highly recommended :)

--Paul

Luis G
April 20th, 2003, 11:42 PM
Paul McKenzie, i studied C++ in depth, i just didn't like or didn't care about it at the time, my mind thinks better in the structured paradigm. And i became even more aprehensive of the C language after reading "Writing Solid Code" by Maguire. Then i learnt ASM, and i became even more fond of structured programming.

btw, i have found some bugs in compilres, a while ago the old BC 3.1 throwed me some bugs into my program, basically, a variable would change its value right after the constructor, even thou it was specified in the constructor to set it to 0, i debug it step by step with a watch, and just after the constructor ended it would change the value back to -1. i didn't like the solution i had to use, which was declaring the variable as "unsigned int", weird huh?

I also found that VC++ 5.0 doesn't like too much parenthesis while doing some arithmetic while assigning a value.

gcc doesn't like function calls in an if statement (specifically semaphore creation), i had to call semget before the if statement and save its returned value into a variable to get the program working fine, unbelievable, but it took me almost 4 hours of madness to discover that it wasn't my code the one that was introducing unexpected behaviour.

Anyway, we've taken this thread off-topic, we were not comparing C against C++. we were talking about wether to use pointers or references. ;)

Paul McKenzie
April 21st, 2003, 09:10 AM
Originally posted by Luis G
Paul McKenzie, i studied C++ in depth, i just didn't like or didn't care about it at the time, my mind thinks better in the structured paradigmWhy do you think that using proper C++ programming techniques and structured programming are mutually exclusive? I'm also talking about structured programming -- safe, C++ structured programming.
btw, i have found some bugs in compilres, a while ago the old BC 3.1 throwed me some bugs into my program, basically, a variable would change its value right after the constructor, even thou it was specified in the constructor to set it to 0, i debug it step by step with a watch, and just after the constructor ended it would change the value back to -1.To be quite honest, that's hard to believe. Borland would have been deluged with tech support calls if that really was the case. I would have to see the code that you wrote that you claim showed the bug. BTW, I have that compiler and have never seen this problem.
I also found that VC++ 5.0 doesn't like too much parenthesis while doing some arithmetic while assigning a value.I would have to see an example of this.Anyway, we've taken this thread off-topic, we were not comparing C against C++. we were talking about wether to use pointers or references. ;) I know :)

However we got here by comparing the 'C' way of doing things (always using pointers) to the C++ way of doing things (a mixture of references / pointers depending on the situation) and wound up here. I'll just state that using 'C' techniques in C++ programs will bite you at some point. For example, do you still use qsort() to sort objects? Guess what -- it's not guaranteed to work for anything but 'C'-structs (POD types). Ever try to bypass constructor of an object by calling malloc() instead of new? Again, not guaranteed to work.

Regards,

Paul McKenzie

KevinHall
April 21st, 2003, 10:52 AM
I have quickly browsed though this thread, and I think that people are taking extreme stances on the subject to drive home their points. However, anyone unfamiliar with this topic in depth should keep in mind that there is usually an exception to every rule.

In c++, it is best to use vectors over arrays.

In many cases this is true. However, if your application is very CPU intensive, there are sometimes arrays are better. For example:
(1) A matrix class. Using a pointer with new to define a (protected) array is usually more efficient than defining a vector of vectors.
(2) In an FFT system analysis program I have been dealing with. I have to aquire and analyze real-time about 1MB/sec of data with even slow P1 and P2 systems. Using arrays instead of vectors here helps optimize the performance.


The dead giveaway is if 'C' programming was a prerequisite to the C++ course. If 'C' programming was a prerequisite to C++, then that shows where the problem was -- it presumed that you need to know C before learning C++ -- absolute nonsense. As a matter of fact, it makes the job harder in converting 'C' minds into C++ minds, as the FAQ I posted a link to describes.

C should not be a prerequisite for learning c++, but it should probably be a requisite nonetheless. There are still many systems and libraries out there written in C that someday a C++ programmer will run into. If he/she does not have any knowledge of malloc/calloc/free or some of the other C ways of doing difficult things (like using # and ## in macros), then he/she will be handicapped.

Anyway, I know that I have picked on a couple of quotes from some very knowledgable and experienced people (both of whom I respect very much) -- all I am trying to do is make sure that someone less experienced knows that there are usually cases where the "rules of general practice" do not apply. One of our jobs as programmers is to determine if we have one of those cases.

Cheers!

- Kevin

Paul McKenzie
April 21st, 2003, 11:11 AM
Originally posted by KevinHall
However, if your application is very CPU intensive, there are sometimes arrays are better. For example:
(1) A matrix class. Using a pointer with new to define a (protected) array is usually more efficient than defining a vector of vectors.
Hello Kevin,

C++ gurus knows that vector of vectors is the easy way of implementing a matrix, but know full well of the drawbacks of nested vector classes. This is why such things such as the libraries at www.boost.org exist that efficiently handle these situations.(2) In an FFT system analysis program I have been dealing with. I have to aquire and analyze real-time about 1MB/sec of data with even slow P1 and P2 systems. Using arrays instead of vectors here helps optimize the performance.Internally, a vector is exactly the same as an array (std::vector uses contiguous blocks of memory). So it depends on what you are doing with the vector that counts. If you are doing nothing different with the vector that you would be doing with an array, then there should be no speed (or very negligible speed difference). If you are inserting stuff in the middle or at the beginning of the vector, then you are using vector in a way that arrays cannot be used. To do the same thing with an array, you would basically do the same thing that vector would do -- allocate new , copy, delete old. Caveat: member functions such as reserve() does wonders for vector if you are calling a lot of push_backs(). Did you utilize it in your testing (that is, if you were calling a lot of push_back's)?
There are still many systems and libraries out there written in C that someday a C++ programmer will run into. If he/she does not have any knowledge of malloc/calloc/free or some of the other C ways of doing difficult things (like using # and ## in macros), then he/she will be handicapped.Believe me, a experienced C++ programmer has full knowledge of these functions, since they know where things such as malloc(), calloc(), qsort(), etc. should be avoided :). Look how much code that purports to be C++ contains malloc(), free(), etc. It takes an experienced C++ programmer to point out that "hey, that can't be done" or "here is the problem of doing it...".

Token pasting macros are neither C or C++, they are just part of the preprocessor.

Regards,

Paul McKenzie

KevinHall
April 21st, 2003, 12:08 PM
I know that token pasting is part of the preprocessor, however I have seen it used much, much more in C to accomplish things like writing "template"-macros. I have rarely seen token pasting in C++ b/c of the ability of C++ to handle templates, namespaces, etc.... Of coarse there are situations where token pasting is useful for C++.

As far as the FFT app is concerned, I use the array mainly as a buffer. Mostly only memory copying is involved. I am not really using any feature that std::vector adds (or simplifies).

C++ gurus knows that ...
Believe me, a experienced C++ programmer has full knowledge of ...

Yes, I agree. I was attempting to write something for those that are not gurus or experienced C++ programmers. (I believe I said that in my last post.) There are many people who check out this site because they are learning C++ and have simple questions (just like the person who started this thread) -- that's all.

By the way, I do believe vectors are better in most situations, that C should not be a prerequisite for C++ and that experienced C++ people do know the limitations of the STL. I have just read too many posts in different threads where people say "this rule always applies."

Regards,

Kevin

KevinHall
April 21st, 2003, 12:19 PM
Back to the original question:

A referece cannot be reassigned to another variable.


double x=1.0, y=2.5;
double &z = x;

z = y; // assigns the value 2.5 to x, not the reference of y to z


Anyway, if you need to reassign references, then a pointer makes more sense.

- Kevin

Luis G
April 21st, 2003, 02:10 PM
Paul McKenzie, i don't have those codes anymore, it was years ago, only one i can possibly get is the gcc and semaphore one.

galathaea
April 21st, 2003, 08:18 PM
Originally posted by KevinHall
However, if your application is very CPU intensive, there are sometimes arrays are better. For example:
(1) A matrix class. Using a pointer with new to define a (protected) array is usually more efficient than defining a vector of vectors.
(2) In an FFT system analysis program I have been dealing with. I have to aquire and analyze real-time about 1MB/sec of data with even slow P1 and P2 systems. Using arrays instead of vectors here helps optimize the performance.
Hmm.. I have yet to see an actual case where arrays are more optimized than properly used vectors (of course, don't push_back everything when the size is statically known -- as they must be for arrays). I have had to do a whole lot of strange and intensive manipulations on data structures, many of which have a backbone that could be represented as a statically sized array or vector, and I have done at several times the profiling to see what would be quicker. Almost always I got the same speed (there was a problem once with the Visual C++ compiler not removing one added layer of indirection on a very very tight loop -- two machine instructions -- but CodeWarrior is always my optimizer of choice and I think I heard -- but haven't checked the disassembly -- that the newer .NET c++ compiler does static indirection elimination optimization properly).

But the best and fastest matrix and FFT codes I have seen used heavy template metaprogramming to build the static data structures in a way that could be used to optimize element-wise the transformation (by forcing inline code through templates, forcing RVO, unrolling loops with templates, etc.). A good example of a matrix class that is available freely online is the one with Blitz++, but it doesn't implement all the features I have seen as regards speed. The FFT examples I have seen benefitted immensely from the translationtime evaluation of the transform coefficient multiplication. But in all these cases, it is the use of static translationtime data structures and not runtime structures like arrays or vectors that form the seat of the speed increases, and a simple seating of the results inside a vector or an array (where the runtime calculations may occur) doesn't seem to in any way be a cause of speed problems.
Also posted by KevinHall
I know that token pasting is part of the preprocessor, however I have seen it used much, much more in C to accomplish things like writing "template"-macros. I have rarely seen token pasting in C++ b/c of the ability of C++ to handle templates, namespaces, etc.... Of coarse there are situations where token pasting is useful for C++.
I use token pasting all the time since I do a lot of API interception and have simple rules for naming my interception functions. I use them to build up the vectors of function pointers used in the interception. I did use to use arrays here, however, but thought they were too unsafe. :)
Also posted by KevinHall
A referece cannot be reassigned to another variable.
Well, neither can a pointer passed by value to a function, at least not visibly outside the function (we are talking memory location here, right?). And if one wanted it only inside the function, it would require setting up an automatic variable to get the new address or using pointer math (for arrays? -- this is the particular unsafe operation which is why one wants to use vectors or smart-pointers with array semantics and bounds checking).

I'm not trying to pick on you Kevin, since I understand what you are trying to say, that one shouldn't unlearn anything about arrays since they may come in handy in one's toolkit when the circumstances dictate. However, I must admit that I started programming (well after the interpreted languages of Logo and BASIC) in c and even moved into c++ with the "help" of Schildt. So I had a lot of c style to my early programming in c++. But as I've continued to study and test my projects, I have found that the only time I use arrays anymore is when I am tossing together a translationtime assert (with array size -1 on false evaluation). And naked pointers (keeping topicality to the thread :)) are only found in my code as private class members. From what I can tell from the c++ community and the recent publications, this seems to be the natural progression, and I think I agree with it.
Originally posted by Luis G
btw, i have found some bugs in compilres, a while ago the old BC 3.1 throwed me some bugs into my program, basically, a variable would change its value right after the constructor, even thou it was specified in the constructor to set it to 0, i debug it step by step with a watch, and just after the constructor ended it would change the value back to -1. i didn't like the solution i had to use, which was declaring the variable as "unsigned int", weird huh?
[...]
gcc doesn't like function calls in an if statement (specifically semaphore creation), i had to call semget before the if statement and save its returned value into a variable to get the program working fine, unbelievable, but it took me almost 4 hours of madness to discover that it wasn't my code the one that was introducing unexpected behaviour.
Actually the BC and gcc "bugs" sound like common programming errors from the description. The BC error sounds like the common problem of mistaken scope and passing stack values, and is common in ctors. The gcc error sounds like scoping and variable lifetime problems. Both of these compilers are quite commonly used by professionals, and although they do have known problems which they list on their respective sites, none of them are as basic to the language as what is suggested. If you however feel you have found some bugs, post them in a new thread and have them publicly evaluated. They are not, however, by any means reasons to not use the language properly except as workarounds are needed, but I understand that was not your point.