Default values instead error handling

Take a look at the following declaration.

Although this isn’t particularly interesting, I have come across this little thing. This declaration is from Unity’s PlayerPref’s class and is an interesting way of solving a problem. The problem is “What should this thing do, if the key doesn’t exist in the player prefs?” While attempting to write something very similar, I thought, I could return an error code, which means the output is a parameter. Bleh. I could throw an exception, which is valid too. Which is also kinda bleh. But here, even though retrieving a float is exceptional, it’s handled elegantly because you don’t need to check an error code or write exception safe boiler plate code. You’re specifying what the value should be in case it doesn’t exist. Which is a case that might be expected. In other words, you’re handling the exceptional cases by configuring it. You’re telling it what you want to do in case it fails. Since this method can only fail in one way to the user (doesn’t exist, can’t get it, etc.), one parameter suffices. If it can fail in multiple ways, this could turn into something terrible as all the parameters tell this thing what to do on failure. Perhaps something better, in that case, might be to pass in a “configure” struct. But that’s kinda bleh too.

This actually has an issue that can cause some pain though. When I was using Unity a long time ago, I remember having a bug where I thought the value was in the player prefs, but really it was just the return value. The GetFloat and SetFloat actually had a slight typo where the keys were not identical. You could imagine the frustration. Although this might be equivalent to not checking the error code return value if the declaration was specified that way.

Anyways, the point is that sometimes an elegant simple solution is also a clever one.

Mac dylib rpath framework bundle explanation

The purpose of this article is to teach you how to properly configure a dylib / framework on the mac and the application linking against it. If you don’t do this properly, you could be in for a long time wasting ordeal. In this article we will describe, in enough detail, how the linking process works in order to get things working and hopefully teach you enough to configure things on your own if you decide to do something in a non-standard way. We will also give you the tools and knowledge required in order to debug issues related to library loading, particularly with rpaths.

The subject
When you load an application, the dynamic linker (it’s actually an application on the mac called dyld I believe), will look at all of the references (symbols) in the application and try to resolve them (perhaps on load, perhaps not, who knows these days). In order to do this, it needs to know what libraries this application depends upon, where the libraries are on the hard drive, and also, what libraries those libraries depend upon so it can load them too, recursively. If the dynamic linker can’t find these libraries, it can’t load them, bottom line. You’ll end up with an error such as “bundle is corrupt, invalid, or missing resources” or some error like that.

Read the rest of this entry »

Pure Functions – Category Theory

What is a pure function? This is more abstract and not specific to C++. I ran across this term while watching a video from Bartosz Milewski at C++ Russia, 2015 on Categories. I felt that this little bit about a pure function can help programmers and when I code, I try to use it frequently.

  1. A pure function has no side effects. Think “functional language”. Or a const function in C++. It doesn’t modify any state.
  2. When called with the same arguments, it always returns the same result. (Referential Transparency)
  3. It can be memoized. Because it doesn’t depend on shared state, you can precompute the results. The example he uses is the Fibonacci sequence. A function that compute the Fibonacci sequence can be precomputed and cached off into a table.
  4. Because there’s no side effects of a pure function and they don’t modify a shared state, it’s easier to move function calls around.

Smart pointer general guidelines

Modern pointer guidelines for C++ are confusing, so I wanted to gather a list of general guidelines for pointer use. I’m sure I’m missing some though that could be added.

Most of these were taken from gotw-91.

  1. Don’t pass a smart pointer as a function parameter unless you want to use or manipulate the smart pointer itself, such as to share or transfer ownership. Only pass a smart pointer if you intend to share ownership.
  2. Prefer passing objects by value, *, or &, not by smart pointer.
  3. Pass by * or & to accept a widget independently of how the caller is managing its lifetime.
  4. Use a * if you need to express null (no widget), otherwise prefer to use a &; and if the object is input-only, write const widget* or const widget&.
  5. Put pointer in class header almost all of the time. Prefer using the pimpl idiom.
  6. You can put a reference in a class header, but it must be set at construction time, passed into the constructor. (dependency injection)
  7. Prefer unique_ptr to shared_ptr
  8. Express a “sink” function using a by-value unique_ptr parameter:
  9. Use a non-const unique_ptr& parameter only to modify the unique_ptr.
  10. Don’t use a const unique_ptr& as a parameter; use widget* instead.
  11. If it can be null, pass widget*, if it can’t be null, use &.
  12. Express that a function will store and share ownership of a heap object using a by-value shared_ptr parameter.
    1. Don’t normally use this because it restricts the lifetime of the caller.
    2. This is used to modify the shared_ptr itself.
    3. void f( shared_ptr& );
  13. Use a non-const shared_ptr& parameter only to modify the shared_ptr.
  14. Use a const shared_ptr& as a parameter only if you’re not sure whether or not you’ll take a copy and share ownership; otherwise use widget* instead (or if not nullable, a widget&).


Getting Qt + CMake to work on the mac (Sierra)

It took me forever to figure this out since the .bash_profile file doesn’t work for gui apps.

sudo vim /etc/launchd.conf
type in: setenv CMAKE_PREFIX_PATH /Users//Qt/5.7/clang_64
grep -E “^setenv” /etc/launchd.conf | xargs -t -L 1 launchctl
restart cmake

Skipping boost and stl libraries while debugging

This trick will allow you to step over boost and stl functions when debugging. It will not allow you to step into any of that stuff. Yippee.
The downside is that if you want to follow where a boost::signal ends up, you won’t be able to unless you already know where it’s going.

  1. Create a file called: boost_stl.natstepfilter
  2. Dump contents below into it.
  3. Put that file into your “C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Packages\Debugger\Visualizers” directory.

Singletons with controlled destruction

I’m not going to debate about why one should or should not use singletons. I’m only going to provide an improvement for the singleton. One of the problems with singletons is that they use a static member. The problem with static members is that they can be destroyed in any order on application exit. If you have more than one singleton, and have dependencies between them, you want to control destruction of the singleton on application exit.

The differences between this and the Super Simple Singleton I previously posted about a couple of years ago are:

  1. The instance is a member of the class, not a function.
  2. There is a destroy() function

The destroy function allows for controlled destruction of the singleton, which is a million times better. When your application exists, and you have more than one singleton and they are dependent upon each other, who knows which one will get destroyed first. This gives you a lot more control over it.

C++ Best Practices

I love best practices. It’s like a jump start or a synopsis of all the things you should do without reading through all the heavy books.

In and out params

For functions, it’s handy to be able to identify what’s an “in” parameter, versus what’s an “out” parameter. I just got done reading an article about the Doom3 engine source code and there was something that I liked.

  1. From this signature you can identify what is an “in” and what is an “out”.
  2. The return type is obviously an “out”.
  3. The “const int val” identifies this as an “in”, even though it’s just an int.
  4. const Data& d1 is an “in”.
  5. For d2, it’s an out, and this is obvious because it takes a double pointer.
  6. For d3, this is also obviously an out. You want the function to fill something out.
  7. All out parameters use pointers, all in parameters use const or const refs.
  8. Never use a parameter as both an “in” and an “out”.

For #6, when you call this function look at what it looks like.

You can tell by looking at how it’s called what is an input and what is an output. If it has an &, you know it’s an out. Except for the return value obviously. You also have a guarantee that counter or data won’t be modified, and it won’t be modified inside the function. The function could copy the value and change it there as a separate variable on the stack, but that requires extra work. This is all about simple guarantees. I really like this approach, and I think I will adopt it for my standards.

Clang omp XCode

How to switch from clang to clang-omp. I am using Yosemite and XCode 6.2.
Some of this was taken from Stack Overflow.

brew install clang-omp
cd /usr/bin
sudo mv clang clang-apple
sudo mv clang++ clang++-apple
sudo ln -s /usr/local/Cellar/clang-omp/2015-04-01/bin/clang-omp++ ./clang++
sudo ln -s /usr/local/Cellar/clang-omp/2015-04-01/bin/clang-omp ./clang
cd /Applications/
sudo mv clang clang-apple
sudo mv clang++ clang++-apple
sudo ln -s /usr/local/Cellar/clang-omp/2015-04-01/bin/clang-omp++ ./clang++
sudo ln -s /usr/local/Cellar/clang-omp/2015-04-01/bin/clang-omp ./clang
cd /Applications/
sudo mv -f * ../../

Create a project in Xcode, using the Hello World code on clang-openmp website for test.
Add “-fopenmp” to Custom Compiler Flags -> Other C Flags in project settings.
Add /usr/lib/libiomp5.dylib to the build phases of project (project settings -> Build Phases -> drag /usr/lib/libiomp5.dylib into Link Binary with Libraries)
Set Header search path: /usr/local/include/libiomp

Don’t forget to add #include


One of the biggest hassles with strings is doing what you want quickly with a one-liner. I recently stumbled across this little gem in boost. boost::algorithm::ends_with(). Basically, it’s a quick check to see if a string ends with another string. No messing around with indices and decrementing iterators, etc.

operator= for a derived class

It didn’t occur to me until now that I have never actually written an operator= for a derived class until now. Or maybe I wasn’t doing it right, or maybe I completely forgot… Here is how you’re supposed to do it:

I don’t ever recall invoking operator=() manually this way. It looks odd, but it should make sense because if you don’t, the base class will never be copied and that’s what you’re explicitly doing.

boost::uuid for unique identifiers

Frequently when I need a unique identifier I might do something silly, like create a static variable and every time an instance of that object is created, I would increment the counter. There are concerns of overflow and other weird things, such as saving and loading these identifiers and syncing the counter back up…

Instead, I would highly recommend using boost::uuid to create a unique identifier. It’s basically a GUID or a UUID. The best part is that it’s cross platform, so it works on mac/linux/windows. It goes something like this:

The syntax is a bit weird for generating a uuid, but that’s how it’s done.

You can use boost::lexical_cast to convert between the uuid and a string. As of right now, boost::serialization can not serialize boost::uuids::uuid objects, for some reason, so the best thing to do is to lexical cast to a string, serialize it, then lexical cast back into a boost::uuids::uuid data type.

Reducing API modifications

A colleague of mind gave me a really cool idea that’s so simple I never thought about it from a design perspective. Sometimes, a function might take several arguments, where each argument represents a configuration value.

If, in the future, you need to add more settings you can add more parameters… But that causes the API to change, which is a huge hassle most of the time. Instead, it’s better to create a struct and pass that in. That way, the API is kept the same. You probably want to initialize the struct to some good defaults though.

So now, it doesn’t matter how many settings you might add in the future, the API doesn’t change. In fact, if you look at the Win32 API, you’ll see they do the same thing. The function takes a struct, and a bunch of stuff you need to set in the struct. This allows the API to be usable well after it should be be killed without the older apps crashing. 🙂

Comments – 01

I think the APIs should be most self documenting. So I prefer to not add any comments unless it somehow helps. Obviously, this doesn’t help if the user wants doxygen documentation. If you do add comments, they should be in the .cpp file only. The reason for this is because reading the .h file is nice, neat, and compact. Otherwise, your header files are massively huge and difficult to digest. But if you do need comments, make sure they’re doxygen style.

So in the cpp file, prefer to have something like this:

There’s no point in adding comments to this function because it should be obvious. But I prefer to have the divider for readability. If you need comments, add them doxygen style, like this:

This of course causes problems. If all of your function comments are in the cpp, you need the cpp to read the documentation. This is okay for me, but not okay if someone else uses the library precompiled. But then again, you’re probably going to have to compile the sources yourself anyways since there’s no guarantee the ABI won’t change between versions of the tool chain.

This is a catch 22. You must build doxygen comments in order to see the documentation. Or ship the source code. I really don’t care because I don’t intend on publishing any of my code… Right now anyways. But I’m not sure if it would make my life easier just putting them all in the .h file.

Plugins for XCode

I’m very happy that there’s a good way to use all the vim stuff within XCode. I’ve been using it for quite a while, and there was nothing I couldn’t do, but I’m also not a super advanced user.

XVim for XCode

I recommend building it from the github repo. As of right now, the current version has a crash bug in it.

Since this post is really about plugins / extensions, I recommend downloading Alcatraz. Alcatraz has quite a few extensions including VVDocumenter, which helps to produce doxygen and appledoc compliant comments. You can change themes, and other useful stuff to make working with XCode suck less.

Intro to boost::signal

boost::signal is the C++ equivalent to a C# delegate. Actually, make sure you’re using boost::signal2, boost::signal is deprecated.

It’s a little confusing at first, but I use the following “template” code below whenever I need to use them. Using a signal requires you have a few things set up. 1) A function that is called by the signal. 2) The signal to call the function. 3) Registering the function with the signal (the slot). 4) Firing the signal. I will show you this through the interaction between two classes.

Register the callback signal handler function.

You can, of course, change the parameters and types to your liking. But you’ll have to figure out how to use boost::bind to do so. See below for the definition of “RegisterSignalHandler”.

Creating the signal.

SignalType is just something to make the code easier to read. We really need two functions, one to fire the signal (if we want to do it this way) and one to register the signal handler. “RegisterSignalHandler” is merely called when you want to register a signal handler to be called when the signal is fired.

Creating the function to fire the signal.

Really any function that has access to “signal_” can fire the signal. In this case, I fire the signal passing in true the first call, and false the second. This calls all functions that have been “registered” (in the order in which they were registered).

Creating the registration function.

Coding Standards

One thing that you can do to help you code better is to see how other people code. In particular, companies. Just reading their coding standards gives you an idea about why they code that way. It may be a little boring, but sometimes it helps and it keeps the code clean. Other times, it’s just style consistency.

For example, I like to write my function methods like this:

The .h file:

The .cpp file:

The reason I like to have my parameters, one on each line is because, if you need to remove or add a parameter, it makes it a little bit easier to identify where in the list it needs to go, or be removed.

Anyways, here are some coding standards you may want to browse:

Insomniac Games coding standards
Google style guide
CoreLinux++ Coding Standards
General Linux C++ Coding Standards

Visual Studio find window formatting

1. Go to HKCU\Software\Microsoft\VisualStudio\8.0\Find
2. Add a new string value called “Find result format” with a value of $f$e($l,$c):$t\r\n where

$f is the filename
$e is the extension
$l is the line
$c is the column
$t is the text on the line

Note:  You don’t have to restart Visual Studio to pick up on your registry changes.

$p      path
$f      filename
$v      drive/unc share
$d      dir
$n      name
$e      .ext

$l      line
$c      col
$x      end col if on first line, else end of first line
$L      span end line
$C      span end col

$0      matched text
$t      text of first line
$s      summary of hit
$T      text of spanned lines

\n      newline
\s      space
\t      tab
\\      slash
\$      $

The one I personally use is this: “$f$e($l,$c)\s-$s\n”

Super Simple Singleton

Here’s a singleton that is pretty clean. No references lying around in the class. There’s nothing special about it, but it’s simple and clutter free, but it’s not templated or anything like that.