Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Page 535, Chapter 16, Section "User-Defined Types", Listing 16-9 #189

Closed
g8151 opened this issue Sep 27, 2020 · 1 comment
Closed

Page 535, Chapter 16, Section "User-Defined Types", Listing 16-9 #189

g8151 opened this issue Sep 27, 2020 · 1 comment

Comments

@g8151
Copy link

g8151 commented Sep 27, 2020

The section correctly describes how to overload the insertion operator "operator<<" as such:

// The user defined type is passed in as a constant reference to prevent
// any unwanted modification since we are technically just printing.
ostream& operator<<(ostream& s, const YourTypes& m);

However, both the book (Listing 16-9: A Program illustrating how to implement an output operator for a vector ) and the sample code define the "operator<<" as such:

// here v is declared without the const keyword.
//This would technically allow abuses such as: See the "ABUSE" section for explanation

template <typename T>
ostream& operator<<(ostream& s, vector<T> v) {

/*
*** ABUSE ***
assuming that the proper template type parameter constraints such as such the ability to default construct are met
*** THIS WOULD SET EVERY ELEMENT TO THE DEFAULT VALUE OF THE UNDERLINING TYPE BEFORE PRINTING. ***

for (size_t i =0; i < v.size();i++) {
v[i] = T{};
}

*/

s << "Size: " << v.size() << "\nCapacity: " << v.capacity() << "\nElements:\n";
for(const auto& element : v)
s << "\t" << element << "\n";
return s;
}

Redefining the operator as: ostream& operator<<(ostream& s, const vector<T>& v)
helps prevent this and also provide compile assistance by generating compile time errors everywhere the the variable is being modified.

suggestions: This would be a good point to emphasized in the book since theoretically speaking, and especially when dealing with large objects and/or user defined types and classes, it is recommended that the insertion operator (operator<<)
takes its second argument as a CONSTANT REFERENCE for performance and safety purposes. Stressing it in that section of the book would probably help clarify the nuance and the reason why it is recommended to passed the second argument as a constant reference.

@JLospinoso
Copy link
Owner

Good suggestion! I will include this update in the revision.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants