isocpp / isocpp/CppCoreGuidelines

Not owned member variables: pointer vs reference

Open
#222 11 comments 0 reactions 1 assignee View on GitHub

@hsutter is already working on this.

Since Dec 21, 2015.

open
Dominant language
CSS
Stars
45.3k
Forks
5.6k
PR merge metrics
No merged PRs in 30d

Description

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?

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.