Search code examples
c++raii

RAII and uninitalized values


Just a simple question:

if I had a simple vector class:

class Vector
{
public:
  float x;
  float y;
  float z;
};

Doesnt the RAII concept apply here as well? i.e. to provide a constructor to initialize all values to some values (to prevent uninitialized value being used).

EDIT or to provide a constructor that explicitly asks the user to initialize the member variables before the object can be obstantiated.

i.e.

class Vector
{
public:
  float x;
  float y;
  float z;
public:
  Vector( float x_, float y_, float z_ )
    : x( x_ ), y( y_ ), z( z_ )
  { // Code to check pre-condition; }
};

Should RAII be used to help programmer forgetting to initialize the value before it's used, or is that the developer's responsibility?

Or is that the wrong way of looking at RAII?

I intentionally made this example ridiculously simple. My real question was to answer, for example, a composite class such as:

class VectorField
{
public:
  Vector top;
  Vector bottom;
  Vector back;

  // a lot more!
};

As you can see...if I had to write a constructor to initialize every single member, it's quite tedious.

Thoughts?


Solution

  • The "R" in RAII stands for Resource. Not everything is a resource.

    Many classes, such as std::vector, are self-initializing. You don't need to worry about those.

    POD types are not self initializing, so it makes sense to initialize them to some useful value.