For me, I prefer having all my variables, not as pointers.
That's a good goal. If you are able to use C++11 or higher, that should be achievable for almost all use cases. The containers from the standard library and smart pointers make that possible. There will be exceptions but they should be rare.
Is it ok to keep all heap-allocated variables dereferenced?
From your posted code, it appears as though you want to use:
class Foo {
private:
Bar b = *(new Bar());
};
While that is synactically valid, it is wrong from a software standpoint. That line leaks memory. You are better off using the much simpler form:
class Foo {
private:
Bar b;
};
If you need to initialize b
using something other than the default constructor, you may use
class Foo {
private:
Bar b = B(...); // Fill in the arguments for B's constructor
};
or even
class Foo {
private:
Bar b = someFunctionThatReturnsB(...); // Fill in the arguments for the function
};
b
is a copy and thenew Bar
object is leaked. Never use naked new. Either use plain values (here:Bar b;
orBar b = Bar()
) or use smart pointers (e.g.Bar b = *std::make_unique<Bar>()
)