3 ms·
> If default parameter values were dynamically bound, compilers would have to come up with a way of determining the appropriate default value(s) for parameters
by jstanley 3y ago
> If default parameter values were dynamically bound,
compilers would have to come up with a way of determining the appropriate
default value(s) for parameters of virtual functions at runtime, which woiuld
be slower and more complicated than the current mechanism of determining
them during compilation. The decision was made to err on the side of speed
and simplicity of implementation, and the result is that you now enjoy
execution behavior that is efficient, but confusing.
Couldn't you store the default value in the same place you store the function pointer? I don't see why it would cost you anything at runtime.
- planede 3y agoWhen would that default value be initialized?
- jstanley 3y agoThe same time the function pointer is initialised, and from the same source. If you like, consider it to be 2 different functions. One takes an argument, one has a fixed value.
- planede 3y agoThe function pointer is initialized at build time, and put into a read-only section in the executable. This is impossible for default arguments, in general. Many of them would need to be dynamically initialized. Anyway, it's more than one way antithetical how default arguments work in C++. It's not Python, C++ doesn't have default argument objects in any shape and form. Default argument expressions are expected to be evaluated at call time, with all of its observable implications. The feature itself doesn't mesh well with virtual functions, but there is no reasonable way to resolve it. You either break the intuitions for virtual functions or to default arguments.
- gpderetta 3y agoValues can be arbitrary objects and a new one need to be provided at every call site: virtual void foo(std::vector<int> x = {10, 20, 30}); You can't just store a single std::vector{10, 20, 30}. You would need to store a (virtual) factory function instead which, while doable, adds more overhead.