Skip to content

Not owned member variables: pointer vs reference #222

Open
@giovannibotta

Description

@giovannibotta

Consider this:

class A {};

class B1 {
 public:
  B1(const A& a) : m_a(a) {}
 private:
  const A& m_a;
};

class B2 {
 public:
  B2(const A* a) : m_a(a) {}
 private:
  const A* const m_a;
};

I feel like the approach taken in B1 is ideal when m_a is always non nullable, while the one taken in B2 is only useful when m_a can be nullable, which also means there has to be logic to check for nullability every time m_a is used in B2.
Now let's consider:

B1 b1(A()); // legal but bad!
B2 b2(&A()); // compiler won't allow it!

I know certain compilers will complain in some cases when trying to reference a temporary, which is good, because in this case it would be a bug.
What are the guidelines on this? Is it ok to use const T& members? Can this case be mentioned?

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions