C++ operator[] mystic

Why do people use at() to get an item out of a std::map? Why don’t they use the [] operator like in other languages? The documentation on cppreference.com says something mystical like this:

“.. performing an insertion if such key does not already exist.” Why? Well, because it is meant to be used like this:

auto pictures = std::map<uint32_t, std::shared_ptr<PictureData>>;
..
auto& picture = pictures[10];
if (!picture) {
    picture = std::make_shared<PictureData>("Picasso", "Las señoritas de Avignon", 1907);
}

If there is nothing on position 10, it creates a default one. PictureData has to be default constructible.

You can use at() instead, it will throw you an exception when you try to access outside of its boundaries.

at()

When using the at() function, if the index is out of bounds, the function will throw an out_of_range exception. This can help catch potential bugs and improve the safety of the code. On the other hand, when using the operator[] method, if the index is out of bounds, undefined behavior can occur, which can lead to difficult-to-debug errors.

operator[]

In general, the operator[] method is slightly faster than the at() function because it does not perform the bounds checking, but the difference in performance is usually negligible. Furthermore, the performance benefit of using operator[] is only significant when the code is run in a tight loop or with very large data structures.

Which one should I choose?

When it comes to choosing between the operator[] and at() functions, it ultimately depends on the specific needs of the application. If safety and reliability are paramount, then the at() function with its built-in bounds checking is the best choice. However, if performance is a top priority, and the code is carefully written to ensure index safety, then the operator[] function can provide a significant speed advantage.

2 real world code reviews compared

I came across this blog post from Python/Django developer Matt Layman, where he compares 2 different cases of code reviews: one where people sat in a room and spent a lot of time talking about style issues, and one where style checking was automated on GitHub and people started talking about the actual changes and problems the code tries to solve. I recommend reading it.

One thing that really interests me is how did the style guide they were not able to automate look like. Maybe AI based style checkers like FYT could have worked?

2 side takeaways: isort and flake8 for Python, which I will try out soon as I’m using Python/Django myself and especially imports are a topic I need to look into and do some refactoring on, it easily can get messy.

I’m curious how the decision finding and agreeing on rules like flake8 look like in a team, it must be a process of its own.

Printing Stack Traces in Python Exceptions: A Comprehensive Guide

Uncover the Root of Errors with Detailed Tracebacks

Encountering errors in Python is inevitable. But with stack traces, you can pinpoint the exact location of an exception and diagnose issues effectively. Here’s a step-by-step guide:

1. Import the traceback Module:

import traceback

2. Utilize Exception Handling:

try:
processEvent() # Call the function that might raise an exception
except Exception as e:
print("Error encountered:", e)
traceback.print_exc() # Print the detailed stack trace

Key Points:

  • traceback.print_exc(): Prints a formatted traceback to the console.
  • Error Message: The print("Error encountered:", e) line displays the error message itself.
  • Traceback Structure:
    • Each line represents a function call leading to the exception.
    • The topmost line indicates the most recent call, and subsequent lines trace the sequence backward.

Example Output:

Error encountered: An error occurred!
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "<stdin>", line 2, in processEvent
Exception: An error occurred!

Leave a comment, or reach out if you have a question.

Additional Insights:

  • Customizing Output:
    • traceback.format_exc() returns the formatted traceback as a string for further manipulation.
    • traceback.print_exception() offers more control over output formatting.
  • Logging Stack Traces: Consider logging stack traces for debugging or analysis purposes.

Troubleshooting with Confidence:

  • By effectively printing and understanding stack traces, you’ll be equipped to resolve Python exceptions efficiently and maintain code stability.

What does ‘nit’ mean in a code review?

Sometimes when reading code reviews we can find comments like this from a colleague:

auto result = std::make_pair<uint64_t, std::string>(64, "hello");;

nit: double semicolon

What is nit in a code review or in a PR?

A nit is a minor finding in a code review that doesn’t significantly affect the functionality of the code but is still technically incorrect. The term comes from ‘nitpicking.

Like a typo in a comment, a semicolon too much, or an extra empty line. The reviewer points out that this is still not correct, but probably would not want you to delay merging the pull request for it.

And here is how we should treat it: if you still work on the PR, you can fix this in one of your next commits, but don’t delay the feature or bugfix integration for it. We all know, waiting for CI can take time, and if you clog CI for this, some people might not be happy.

Infographic for code review abbreviations

Infographic showing nit in code reviews and other abbreviations and their meaning

I created this infographic showing common code review abbreviations. Feel free to share or download, and please let me know if you know another one that should be on this list.

More to read

To learn more about common “slang” used in code reviews, I have compiled a list in this blog post, where you find explanations to abbreviations such as +1, WIP, LGTM and others.

By Thomas, updated on Jan 31, 2025.