> When I am in doubt about this kind of thing, I make a little class with an
Actually I have no doubts, I'm fairly certain that this a second gcc bug
involving a spurious warning that I found. The first one was recently fixed,
sort of. The spurious warning was triggered in std::vector's bowels, in
certain situations. As far as I can decipher the bug updates they fixed it
by tweaking std::vector's code to avoid triggering the spurious warning; but
the warning was bogus.
> external constructor and destructor and look at what is called where. It's
> easy to be mislead by the behaviour on simple types like "int".
That sounds like a reasonable suggestion, so:
#include <iostream>
struct my_optional {
int value{0};
my_optional()
{
std::cout << "constructor" << std::endl;
}
~my_optional()
{
std::cout << "destructor" << std::endl;
}
const int &operator*() const
{
return value;
}
};
const int &get_my_optional(const my_optional &o)
{
return *o;
}
int main()
{
my_optional opt;
const int &value= *opt;
std::cout << "value: " << value << std::endl;
return 0;
}
Result:
constructor
value: 0
destructor
UPDATE: I'm now fairly sure that this has nothing to do with any cockamamie
temporary returned from any cockamamie function. The following also trips
this warning. Replacing the "int &&def_val" parameter with "int defval"
fixes this warning:
#include <optional>
#include <utility>
const int &optional_arg_or(std::optional<int> &def,
int &&def_val)
{
def = def_val;
return *def;
}
int gimme()
{
std::optional<int> def;
const int &v=optional_arg_or(def, 0);
int bologna=v;
return bologna;
}
int salami()
{
std::optional<int> def;
def = 0;
return *def;
}
gimme() and salami() do the same thing, but gimme() barks, and changing the
parameter to "int def_val" shuts it up. Definitely a gcc bug.