Articles & Books

Quick Q: Need of a weak_ptr in C++11

Quick A: To keep a pointer on a ressource without owning it.

Recently on SO:

Need of a weak_ptr in C++11

The second half of that statement should be clear: if a pointer is not an owning pointer then the object it is pointing at might be deleted by whatever software is the owner - and then you'd have the standard dangling reference.

So this issue is: you've got objects owned by some piece of software which is letting other software have access to it - but the other software won't share the ownership. So the owner can delete it at any time and the other software needs to know it's pointer is no longer valid.

Maybe an example would help:

You've got some piece of software watching a camera pointing out your window to a bird feeder and it is identifying birds at the feeder, which come and go. Each bird at the feeder has an object created by this software when it arrives at the feeder, and the object is deleted when the bird flies away.

Meanwhile, some other software it taking a census. Every 10 seconds it grabs from the feeder-watching software a collection of the birds at the feeder. Every 100 seconds it emits a report of which birds were at the feeder for the entire 100 seconds.

Because the data for a bird is big the census-taker doesn't copy the data. It merely gets, every 10 seconds, a collection of pointers from the feeder-watcher.

To make it necessary to use weak pointers, let's say the feeder-watcher only provides pointers to birds which have arrived in the last ten seconds, not the ones which have been there. That is, there is no notification that birds have disappeared.

By using weak pointers it can know, at report time, which of the birds are still there, and when they arrived (but not when they left).

(Maybe I'll think of a better example later.)

Fast incremental sort -- Lars Hagen

Lars Hagen describes in his blog post a strategy to solve the problem of a fast incremental sort.

Fast incremental sort

by Lars Hagen

From the article

I recently came across the need for an incremental sorting algorithm, and started to wonder how to do it optimally.

The incremental sorting problem is described here, and is an “online” version of partial sort. That is, if you have already sorted kk elements, you should be able to quickly sort k+1k+1 elements, and so on.

Incremental sorts can be useful for a number of cases:

  • You want sorted items, but you don’t know how many elements you’ll need. This could often happen when you are filtering the resulting sequence, and you don’t know how many items will be filtered out.
  • You are streaming the sequence, so even though you want the whole sequence, you want the first elements as quickly as possible.

We’ll see how branch misprediction and other constant factors can make the naive asymptotically optimal version far slower than a practical implementation.

The Ultimate Question of Programming, Refactoring, and Everything

Yes, you've guessed correctly - the answer is "42". In this article you will find 42 recommendations about coding in C++ that can help a programmer avoid a lot of errors, save time and effort.

The Ultimate Question of Programming, Refactoring, and Everything

by Andrey Karpov

From the article:

The scope of my interests − the C/C++ language and the promotion of code analysis methodology. I have been Microsoft MVP in Visual C++ for 5 years. The main aim of my articles and work in general - is to make the code of programs safer and more secure. I'll be really glad if these recommendations help you write better code, and avoid typical errors. Those who write code standards for companies may also find some helpful information here.

Overload 132 is now available

ACCU’s Overload journal of April 2016 is out. It contains the following C++ related articles.

Overload 132

From the journal:

The Tao of Scratch
Scratch is an environment designed to help young people learn to code. Patrick Martin walks us through it. by Patrick Martin

Knowledge-Sharing Architects As An Alternative to Coding Architects
Should architects write code? Sergy Ignatchenko explores this controversial subject. by Sergey Ignatchenko

QM Bites: Understand Windows OS Identification Preprocessor Macros
There’s confusion between user-defined and predefined Windows 32/64-bit operating-system identification macros. Matthew Wilson shines light on the issue. by Matthew Wilson

Why Collaboration is Key for QA Teams in an Agile World
Agile processes can have an impact on QA departments. Greg Law considers how they can adapt to survive and even thrive. by Greg Law

How to Diffuse Your Way Out of a Paper Bag
Diffusion models can be used in many areas. Frances Buontempo applies them to paper bag escapology. by Frances Buontempo

Stufftar
How do you quickly transfer data from one machine to another? Ian Bruntlett shows us the bash script he uses. by Ian Bruntlett

QM Bites: looping for-ever
Never-ending loop constructs can confound user and compiler in subtle ways. Matthew Wilson offers advice to maximise portability and transparency.

Using Enum Classes as Bitfields
Scope enums have many advantages over standard enums. Anthony Williams shows how to use them as bitmasks. by Anthony Williams

9.7 Things Every Programmer Really, Really Should Know
Most of us have heard of the twelve step program. Teedy Deigh introduces a 9.7 step plan for programmers.

Quick Q: Is Stephen Lavavej's Mallocator the same in C++11?

Quick A: No, it has changed.

Recently on SO:

Is Stephen Lavavej's Mallocator the same in C++11?

STL himself has an answer to this question in his STL Features and Implementation techniques talk at CppCon 2014 (Starting at 26'30).

The slides are on github.

I merged the content of slides 28 and 29 below:

#include <stdlib.h> // size_t, malloc, free
#include <new> // bad_alloc, bad_array_new_length
template <class T> struct Mallocator {
  typedef T value_type;
  Mallocator() noexcept { } // default ctor not required
  template <class U> Mallocator(const Mallocator<U>&) noexcept { }
  template <class U> bool operator==(
    const Mallocator<U>&) const noexcept { return true; }
  template <class U> bool operator!=(
    const Mallocator<U>&) const noexcept { return false; }

  T * allocate(const size_t n) const {
      if (n == 0) { return nullptr; }
      if (n > static_cast<size_t>(-1) / sizeof(T)) {
          throw std::bad_array_new_length();
      }
      void * const pv = malloc(n * sizeof(T));
      if (!pv) { throw std::bad_alloc(); }
      return static_cast<T *>(pv);
  }
  void deallocate(T * const p, size_t) const noexcept {
      free(p);
  }
};

Note that it handles correctly the possible overflow in allocate.

Quick Q:Is it possible in C++ to iterate over a std::map with unpacked key and value?

Quick A: An easy solution is not supported by the standard, it may come later.

Recently on SO:

Is it possible in C++ to do std::map<> “for element : container” iteration with named variables (eg, key and value) instead of .first and .second?

You could write a class template:

template <class K, class T>
struct MapElem {
    K const& key;
    T& value;

    MapElem(std::pair<K const, T>& pair)
        : key(pair.first)
        , value(pair.second)
    { }
};

with the advantage of being able to write key and value but with the disadvantage of having to specify the types:

for ( MapElem<int, std::string> kv : my_map ){
    std::cout << kv.key << " --> " << kv.value;
}

And that won't work if my_map were const either. You'd have to do something like:

template <class K, class T>
struct MapElem {
    K const& key;
    T& value;

    MapElem(std::pair<K const, T>& pair)
        : key(pair.first)
        , value(pair.second)
    { }

    MapElem(const std::pair<K const, std::remove_const_t<T>>& pair)
        : key(pair.first)
        , value(pair.second)
    { }
};

for ( MapElem<int, const std::string> kv : my_map ){
    std::cout << kv.key << " --> " << kv.value;
}

It's a mess. Best thing for now is to just get used to writing .first and .second and hope that the structured bindings proposal passes, which would allow for what you really want:

for (auto&& [key, value] : my_map) {
    std::cout << key << " --> " << value;
}