0

I have a function declaration where one argument is a class constructor default parameter like shown:

int someFunction(int seed, int x, Metrics& metrics = Metrics(size));

where size is a const double initialized to 41.64

I'm porting this function to Linux, and am running into problems with GCC (v4.8.5). The code compiles fine in MS Visual Studio 2008, but not with GCC.

I've tried dynamic_cast<Metrics&>(Metrics(size)) but that doesn't work.

The error I'm getting from GCC is:

error: could not convert 'Metrics(4.164e+1)' from 'Metrics' to 'Metrics&'

  • 4
    VC++ has a default-on extension for binding temporaries to non-`const` references. This is not allowed by the language. The extension is hard to disable as disabling language extensions breaks a bunch of platform specific headers. – François Andrieux May 14 '19 at 19:52
  • 1
    Related/possible duplicate : https://stackoverflow.com/questions/16380966/non-const-reference-bound-to-temporary-visual-studio-bug – François Andrieux May 14 '19 at 19:53
  • Thanks for the VC++ tip @FrançoisAndrieux –  May 14 '19 at 20:00
  • 2
    If you really need a mutable temporary object (why?), I'd probably just go with two functions: `int someFunction(int seed, int x, Metrics& metrics) { ... } int someFunction(int seed, int x) { Metrics metrics(size); return someFunction(seed, x, metrics); }`. – melpomene May 14 '19 at 20:21
  • On a side note, unrelated to question, is a fact that this function will create havoc in future for maintaining binary compatibility! Changing the size of Metric class (sizeof(Metric)) needs recompilations. – Viren May 14 '19 at 20:30
  • @Viren That's normal and expected, and nothing to do with this question – M.M May 14 '19 at 21:58
  • 1
    You could change to `int someFunction(int seed, int x, Metrics const& metrics = Metrics(size));`, if the function doesn't modify the metrics – M.M May 14 '19 at 21:59
  • 1
    @FrançoisAndrieux The situation with Windows headers may be improving. https://learn.microsoft.com/en-us/cpp/build/reference/permissive-standards-conformance?view=vs-2019 says `/permissive-` (which corrects this behavior among others) "is compatible with almost all of the header files from the latest Windows Kits". – aschepler May 15 '19 at 22:44

1 Answers1

0

After reading the question linked by @FrancoisAndrieux, I got this compiling on GCC by changing to:

int someFunction(int seed, int x, Metrics* metrics = &Metrics(size));
  • Looks quite evil to me though. What are you supposed to do with that pointer? Write to the object it points to? Even delete it? – ypnos May 15 '19 at 22:24