0

I have one class with a constructor that takes another struct as a parameter, and that has a default value. Something like this:

class A
{
public:
A(someStruct st = someStruct::defaultStruct());
};

I've run a static analyzer on my code and it says that this parameter should be const ref. But it's kinda ref to a temporary, though I'm making a copy of it the the constructor, but still I'm confused should I do it const ref.

someStruct::defaultStruct() is something like

static someStruct someStruct::defaultStruct()
{
    return { 0, 0 };
}
Bruice
  • 63
  • 6
  • Depends of `someStruct`. (size, trivial copy/destructor)? – Jarod42 Jul 13 '21 at 14:33
  • @Jarod42 someStruct doesn't have a cope constructor and d-tor, it has few fields including other template structs with simple constructors also without d-tor and other – Bruice Jul 13 '21 at 15:03
  • What is your question? – eerorika Jul 13 '21 at 15:09
  • Related: [pass-by-value-or-const-reference](https://stackoverflow.com/questions/18659043/pass-by-value-or-const-reference). Default argument doesn't matter. – Jarod42 Jul 13 '21 at 15:09
  • @eerorika I'm concerning about having reference to a temporary in this case. Though it won't go out of scope, and later in my c-tor I will make a copy out of it, but could it be possible downside or maybe it's just a terrible bad style, like using goto, for ex. – Bruice Jul 13 '21 at 15:14
  • const ref is not problematic here, and is a good default. – Jarod42 Jul 13 '21 at 15:16

1 Answers1

0

Analyzer says it needs to be const& because someStruct::defaultStruct() returns a temporary value. You need a code like this:

A(const someStruct& st = someStruct::defaultStruct());

Because only const& can bind to temporary as a default value for your argument.

Afshin
  • 8,839
  • 1
  • 18
  • 53
  • @Jarod42 No it is not. And he says his *analyzer* says this, not compiler. But in general, code should be like this. – Afshin Jul 13 '21 at 14:38