Default arguments have to be bound at compiled time - why? [closed]

寵の児 提交于 2020-01-03 17:11:49

问题


Why was C++ designed like this?...

(This question is different, but intimately related to

Not possible: this pointer as a default argument. Why? )


回答1:


Actually, that's not completely accurate. The restrictions are:

8.3.6 Default arguments [dcl.fct.default]

7) Local variables shall not be used in a default argument. [ Example:

void f() {
int i;
extern void g(int x = i); //error
// ...
}

—end example ]

8) The keyword this shall not be used in a default argument of a member function. [ Example:

class A {
void f(A* p = this) { } // error
};

So, this and local variables can't be used as defaults.

For example, the following is valid:

int a = 1;
int f(int);
int g(int x = f(a)); // default argument: f(::a)
void h() {
  a = 2;
  {
    int a = 3;
    g(); // g(f(::a))
  }
}

g will be called with the value f(2), which isn't a compile-time constant. This is an example straight from the standard.

The reasons it's like this is the usual: there either wasn't a proposal for it, or it was rejected, deemed not necessary or too difficult to implement.




回答2:


Default arguments are values to a parameter due to be used in the function's body. This variable's(i.e. parameter) value may be overridden depending upon how the function is called. But while its not - the default argument is the value to this variable - and a value must be defined. It this value has to be dynamic - not to be bound during compile time - then perhaps a separate function should be better used to compute that value and does not seem fit in the default arena. Also for such a scenario C++ already has the right mechanism - Polymorphism by function overloading.

Consider this: You need to call a function Fn either with a param v or else it should default to Fn(x) here both v and x are variables.

Instead of going through having to have default parameters this could be easily implemented using function overloading.

BOOL x;

VOID Fn(BOOL v)
{
     ...
}

VOID Fn()
{
    Fn(::x);
}

VOID Main()
{
    ::x = ...; // Variable x's value is altered

    Fn(FALSE);
    Fn();      // Param value defaults to value of x
}

This enforces the programmer to write a better code which is likely to be worth its while in the longer run.



来源:https://stackoverflow.com/questions/12903724/default-arguments-have-to-be-bound-at-compiled-time-why

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!