C + + practical skills explanation

Source: Internet
Author: User

In quasi-standard C + +, the restrictions on the value of the default variable are very vague. Based on this, many compilers allow developers to include default variable values in function declarations, pointers and references to functions, pointers to member functions, and typedef declarations.

Please take a look at the following procedure:

struct A
{
void func(int x=5)
{
}
};
void g(int n=12)
{
}
// 根据C++标准,不能在以下声明中使用缺省变量值。
void (*pf)(inti=120);
void (A::*pmf)(int j=50);
typedef void (*PF)(inti=100);
// 函数的引用
typedef void (&PRF)(inti=100);
int main()
{
pf=g;
PF pf2=g;
pmf=&A::func;
A a;
//这些调用使用了哪些缺省值?
pf();
pf2();
(a.*pmf)();
}

A::func () and G () have the default variable value, which is reasonable. However, the pointer pmf,pf and TYPEDEFPF also define the default variable values. According to the C + + standard, this is not standard.

One of the problems with the actual use of this code is that the default values provided in these declarations are inconsistent with the values provided by the A::func () and g () functions. That is, many compilers use this code as a nonstandard extension. When the G () function is invoked, my compilation will use 120 as the default for PF, but for PF2 it uses 100 as its default value.

As a rule, you should avoid using pointers to functions, pointers to member functions, and the values of default variables named by typedef. Even if your compiler accepts them, it may not be accepted in later versions. Also, the code reduces the dexterity of the program, and it can mislead developers who cannot tell which compiler receives the default variable. In the legitimate code that uses these default value values, the suggestion here is to add some necessary comments to illustrate which default variable values are required.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.