Tests: Fix reliance on undefined behavior of cm::optional

The test for cm::optional assumed that *opt would return a reference
to a non-constructed object if opt.has_value() is false. However, on
certain systems that build CMake with flags to harden the build,
this condition aborts rather than returning the invalid reference.
Fix this by getting the reference only when the cm::optional is
known to actually have a value.

Fixes: #19964
Status Job ID Name Coverage
  External
passed cdash

passed cmake-dash3win10-windows-release-ninja

passed cmake-hythloth-linux-debug-makefiles+sphinx

passed cmake-minoc-linux-release-lint-iwyu-tidy

failed cmake-moonshade-osx-debug-ninja

passed cmake-moonshade-osx-release-makefiles

passed cmake-terfin-windows-release-vs2019

passed ghostflow-check-master

passed ghostflow-check-release

passed ghostflow-stager

passed cdash

passed cmake-dash3win10-windows-release-ninja

passed cmake-dash3win10-windows-release-ninja

passed cmake-dash3win10-windows-release-ninja

passed cmake-dash3win10-windows-release-ninja

passed cmake-dash3win10-windows-release-ninja

00:20:27

passed cmake-hythloth-linux-debug-makefiles+sphinx

passed cmake-hythloth-linux-debug-makefiles+sphinx

00:44:09

passed cmake-hythloth-linux-debug-makefiles+sphinx

passed cmake-hythloth-linux-debug-makefiles+sphinx

passed cmake-hythloth-linux-debug-makefiles+sphinx

passed cmake-minoc-linux-release-lint-iwyu-tidy

passed cmake-minoc-linux-release-lint-iwyu-tidy

passed cmake-minoc-linux-release-lint-iwyu-tidy

passed cmake-minoc-linux-release-lint-iwyu-tidy

passed cmake-minoc-linux-release-lint-iwyu-tidy

00:14:12

failed cmake-moonshade-osx-debug-ninja

00:15:42

failed cmake-moonshade-osx-debug-ninja

failed cmake-moonshade-osx-debug-ninja

failed cmake-moonshade-osx-debug-ninja

failed cmake-moonshade-osx-debug-ninja

passed cmake-moonshade-osx-release-makefiles

passed cmake-moonshade-osx-release-makefiles

00:12:50

passed cmake-moonshade-osx-release-makefiles

passed cmake-moonshade-osx-release-makefiles

passed cmake-moonshade-osx-release-makefiles

passed cmake-terfin-windows-release-vs2019

00:37:11

passed cmake-terfin-windows-release-vs2019

passed cmake-terfin-windows-release-vs2019

passed cmake-terfin-windows-release-vs2019

passed cmake-terfin-windows-release-vs2019

passed ghostflow-stager

passed ghostflow-stager

passed ghostflow-stager

passed ghostflow-stager

passed ghostflow-stager

passed ghostflow-stager

passed ghostflow-stager

passed ghostflow-stager

passed ghostflow-stager

passed ghostflow-stager

passed ghostflow-stager

passed ghostflow-stager