std::deep_ptr

std::deep_ptr aka deep copying smart pointer has not yet been introduced to the STL though several C++ experts have proposed an implementation in the past. See n3339.pdf for one such proposal and a list of possible implementations.

In this post I want to share my implementation of deep copying pointer I recently came up with. Its interface is virtually identical to std::unique_ptr with the exception of additional cloner template parameter (a policy class) that specifies how deep copies are to be made. By default the pointer is copied by doing return (p ? new T{ *p } : nullptr); that is by invoking the copy constructor of T.

My example program illustrates how to create a cloning policy for polymorphic types; in other words how to make deep copies when deep_ptr<Base> actually points to some struct Derived : Base and types in a given inheritance hierarchy implement virtual S* clone():

Finally, and just like the std::unique_ptr, my pointer type can be used with a custom deleter:

del will be called on a pointer managed by p when it goes out of scope or when p is assigned to.


Example program on my GitHub account: deep_ptr.cpp. The implementation: deep_ptr.hpp.


Rounding floating point numbers and constexpr

Good friend asked me a while ago how to round float or double to N digits of precision. Given 0.0123456789 and N = 7 how to get 0.0123457000 as the result. The only way to round numbers (inside a machine) I could think of was to multiply them by 10 ^ N (ten raised to the power of N), cast the result to some type of int effectively stripping the fractional part, followed by a cast back to a floating point representation and division by same 10 ^ N:

Or something to that effect. Translated to C++:

Then he added the dreaded do it fast,… and just as I was about to tell him to take a long walk off a short pier I remembered something about constexpr and doing arithmetic at compile time.

Looking at the implementation above I decided to start with computing the power of 10 at compile time. My first approach was a recursive template struct power_of with a partial specialization, the recursion stop, for the power of zero case (and a helper power_of_v variable declaration):

This allowed me to write power_of_v<10, 3, float> to compute at compile time the 3rd power of 10 stored as type float.
I also created a recursive constexpr function since those too can be evaluated at compile time:

With it I could write power_of_f<float>(10, 3) and it would be the equivalent of using the recursive template struct above.
I decided to think big and used std::uint64_t as the base and unsigned char as the exponent type of the computation. Hopefully overflow was not going to be an issue…

Next I moved onto rounding the floating point number to an integer type (after it has been multiplied by 10 ^ N) and quickly realized a simple type cast was not going to cut it. std::round does much more than that; it considers how close the number to be rounded is to the integer representation of it, ex.: given 0.49 is it closer to 0 or 1. It then rounds it to the closest whole number. Moreover, it considers the sign and rounds in different direction if the number is positive vs negative.

This meant I needed to determine (at compile time) whether the number is positive or negative:

Compute the absolute value of a given number:

And round the number based on the proximity to its integer representation while considering the sign:

Putting it all together and adding some sanity checks resulted in this floating point, compile time (as long as all parameters are constexpr), rounding function which produced the same exact results as its runtime equivalent:

The if statements are there to guard against number overflows. It is better to not round at all in such cases than to return garbage values, or at least this is my attitude regarding error handling in this case.

Here is a test program I created while testing my implementation; it allowed me to easily compare compile time results against the reference std::round based approach.

1: 0.0000000000
2: 0.0100000000
3: 0.0120000000
4: 0.0123000000
5: 0.0123500000
6: 0.0123460000
7: 0.0123457000
8: 0.0123456800
9: 0.0123456790
10: 0.0123456789

Test program output.

The example program on GitHub: round.cpp. The floating point rounding implementation (sprinkled with comments and decorated with template concepts for good measures): round.hpp.


Given the way float and double are represented on the level of bits it is impossible to round them exactly. You can only do so much and come so close to being exact. Playing with the example program’s value and type of variable v as well as different parameters to setprecision stream modifier will illustrate what I mean…



UPDATE

Shout out to Ben from thoughts-on-coding.com for suggesting another runtime solution (code below)!

San Diego C++ Meetup

San Diego C++ Meetup 25th meeting featuring JFrog and Conan!

https://www.meetup.com/San-Diego-CPP/
https://www.meetup.com/San-Diego-CPP/events/277115020/

Agenda

Welcome slides – goals we would like to achieve in San Diego C++ Meetup
This meeting – Hosting JFrog: Conan Package Manager for C++ in Practice

If time permits:
* Shout Out to a great C++ blog – “Vorbrodt’s C++ Blog”
* 3 cppquiz questions
* 2 years of San Diego C++ Books recommendations – a recap!
* An additional New book for this month – “Ace the Trading Systems Developer Interview” With an example of one of the questions

Featuring:
* Conan Package Manager for C++ in Practice

The Conan package manager for C++ is useful in both simple and advanced development environments. Join the Conan team to see it in action, with a simple demo using OSS libraries and tools from ConanCenter, and a more complete demo showing how to create and upload a package including different binaries for different platforms to a private repository. Also, learn about many other unique and innovative advanced Conan features along the way.

Jerry Wiltse Bio: Jerry is a member of the Conan development team, and has been dedicated to build engineering for C and C++ since 2016. He is an avid open-source enthusiast but also deeply focused on enterprise development environments. He is also the narrator and creator of the Conan learning track on the JFrog Academy.

Fun with TCP sockets

The purpose of this post is not to teach you about posix sockets; there’s plenty of that already. Instead I want to share two simple classes I implemented last night which encapsulate two types of tcp sockets: listening server socket and a client socket. These sockets as well as my recent serializer code will be the foundation of a light-weight RPC system I plan on designing and teaching to my colleagues at work and elsewhere.
I will try to illustrate what happened under the hood of frameworks like gRPC, Thrift, or a much simpler XML-RPC

The server’s socket only job is to bind to a local port and listen for incoming connections. The client socket represents a connection to a server. It can be created either by the server socket using its private constructor, or by the user with its public constructor.

The difference between my implementation and what I commonly see online is that my design (not necessarily better than others) is event driven, meaning you do not pull on the client socket to receive incoming data. Instead the receive function dispatches an event when data arrives; all you have to do is put the method in a while loop to keep receiving incoming packets. Here’s the event handler and the receive loop:

Here the socket’s event handler converts the incoming bytes to a string, and if not empty prints it to standard output. The loop blocks until more data arrives, dispatches the event when it does, then goes back to sleep. This is a part of a simple echo client and server I created to test the socket code; it will be shown further down this post.

The server’s handler for incoming connections is a bit more complicated; it defines what to do with the newly created connection socket, as well as what that socket should do when it received data. You’ve been warned:

Upon receiving a new connection the handler prints out some basic info about the connecting machine, like host name, IP address, and the originating port number. It then tells this socket that, when data arrives on it from the client machine, it should convert it to a string, print it, and send the data right back to where it came from. It is not a true echo server, because the string is reversed before being sent to the client, but for the purpose of this exercise it will suffice. It only prints and sends the data back if it is not an empty string. Finally it looks for a special keyword ‘die’ that instructs the server to shut down.

The client on the other hand waits for incoming data from the server on the main thread, while a background thread reads user input, line by line, checks if it isn’t an empty line, checks for keyword ‘q’ which instructs it to disconnect from the server, and finally sends the data and waits for an event. This event is signaled only once the response comes back from the server, so that the keyboard input and programs output stay nicely separated on their own lines. Client loop below:


The socket code is located on my GitHub page: sockets.hpp, along with the echo client: echo_c.cpp and server: echo_s.cpp.

Better serializer

In my last post I described a light-weight serialization framework I recently implemented (video where I go over it in detail). After receiving great feedback from r/cpp I have implemented several improvements that were suggested to me: better unpack transform signature, safer unpacking code, unpack casting iterator just to name a few.

The latest code is available on GitHub; the serializer source lsf.hpp, and usage example lsf.cpp.

Video where I describe the changes in greater detail:

Light-weight serialization framework

UPDATE: Better serializer

In my very first YouTube Channel video I discuss in detail the design of a serialization framework I came up with in response to a question I was recently asked. In this post I want to give a brief overview of how it works and how to get started using it.

The primary goal was to create a serialization framework that is uncoupled from the types it operates on, meaning no class nor struct needs to inherit any sort of

By default every type is packed by doing bitwise copy from its memory location into a

The code above packs a single

It is possible to perform type conversions inside the pack and unpack transforms:

Above code illustrates it: every

Here I define how to serialize

Having defined transforms for simple types we can now add more complex types, let’s say

The packing code is trivial: pack the size of the vector followed by packing each entry one at a time. Notice here I am calling

One thing I have not yet mentioned is an optimization I introduced into the code: before types are packed the exact amount of memory is reserved inside the resulting

There is a void pointer parameter but in this case it is ignored. However it is required to compute sizes of more complex types like strings; that is because in order to store the pack size procs inside an internal data structure each one needs to be wrapped inside the default lambda. This lambda gets the memory location of each type as

Here I tell the framework how to compute the number of bytes needed to serialize strings.

I initially tagged each type with a unique value so that I could verify it during unpacking to catch errors like packing an int but trying to unpack a string. This type tagging became more complicated than I first anticipated so I got rid of it, though I may revisit it and add an additional packing and unpacking functions that perform this verification optionally.

As always, the code is available on my GitHub page.
The framework is a single header file: lsf.hpp. Example program: lsf.cpp.


The future of C++

I hope the title of this post got your attention! What I really mean is the future direction of this blog…

In 2019 I created 85 short articles, in 2020 I blogged only twice. The last 12 months have pulled my attention away from this site and toward mentoring other engineers at work by hosting online C++ and OO classes. I have mentored tens of engineers over the span of 19 classes in the past 6 months, totaling around 25 hours of recorded material and thousands of lines of code.

I have always enjoyed sharing my knowledge by teaching, this is why this blog came into existence and the feedback I received from it has been fantastic (and humbling). The interactive classes I hold have been particularly rewarding to me and I decided to open them up to the world.

Going forward I want to hold live and interactive classes like I do at work, but open to anyone on the internet. Perhaps also 1 on 1 sessions to help others with their day to day coding challenges. All of this I will publish on my YouTube Channel where you can already find one of my classes I held earlier this week.

I hope you will subscribe and follow me there. I also want to ask you for topics and questions you would like to see me tackle as I reason through the design and implementation of my solutions.

Finally I wanted to add that I will continue to blog. Hopefully the world will soon return to normal and I can get back to what I enjoy the most: C++

Stay safe!