1

I looked at a piece of code and I am trying to understand how it works and so here is a minimal working example

template <typename T>
class A
{
public:
    A() : _mem(T()) {};
private:
    T   _mem;
};

The first thing I was not exactly clear about is the initialisation of _mem in the initialiser list. What is this technique(?) called? If I look in the debugger _mem is set to 0. If there is a c++11 way to do the same thing could I receive some comments on that?

0

2 Answers 2

2

This is just to safeguard against an uninitialized A::_mem when T is a POD type or a built-in type (like an int). Using a constructor initializer list of : _mem(T()) will default construct a T and initialize _mem with it. For example:

struct POD {
    int num;
};

// ...

A<POD> a;

Here, a._mem would be unitialized (in this case, this means a._mem.num is unitialized.) The : _mem(T()) prevents that from happening and will initialize a._mem.num to 0.

However, since C++11 you can just use inline initialization instead:

template <typename T>
class A {
public:
    A() {};
private:
    T _mem{};
};

T _mem{}; will default-construct _mem, which in turn means POD::num will be default-constructed, which for an int means it will be zero-initialized.

Sign up to request clarification or add additional context in comments.

Comments

1

If this has a name, I don't know it.

What's happening:

T() constructs a temporary T and Zero Initializes it.

_mem(T()) makes _mem a copy of the temporary T. Note: A modern compiler will almost certainly elide the copy and simply zero initialize _mem. This still requires that T be copy-or-moveable, so _mem(T()) and _mem() are not exactly the same.

The only relevant C++ 11 difference I can think of is you can use curly braces, _mem{T{}}, for List Initialization. Not useful here, but very useful in other circumstances.

2 Comments

After I posed the question I "realised" that you can say int a = int(); and it is intuitive to think that int() is a call to some sort of default constructor which would set a to zero. I just wanted some C++ jargon to be honest :). Thanks for the C++11 supplement as well !
Sorry about missing that bit. I focused in too closely the syntax you asked about and didn't mention the really easy improvement in C++ 11, inline initialization.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.