在开发较旧的c++标准期间,嵌套函数的想法被认为是无用的,因为它的用法基本上被另一个概念如面向对象编程所涵盖;或者它不是为了简化而实施的?
was the idea of nested functions considered to be useless during the time of developing older c++ standard, because its usage is basically covered by another concept like object-oriented programming; or it wasn't implemented just as a matter of simplification?
嵌套函数 - 有用 - 需要包含函数的堆栈帧作为上下文.看看这个:
Nested functions - to be useful - need the stack frame of the containing function as context. Look at this:
class Foo()
{
void Tripulate()
{
int i=0;
void Dip()
{
// ...
}
int x = 12;
for(i=1; i<=3; ++i)
{
int z= 33;
Dip();
// ...
}
}
}
Dip() 应该访问哪些值?
Which values should Dip() get access to?
没有?您刚刚或多或少地复制了(匿名)命名空间的功能.
只给 i,因为它是函数之前定义的唯一一个?
仅适用于 i 和 x,因为它们与 Dip()
在 sam 范围内?编译器是否必须确保 x
的构造函数已经运行,或者这是你的工作?
z呢?
None? you have just duplicated the functionality of (anonymous) namespaces, more or less.
Only to i, because it's the only one defined before the function?
Only to i and x, because they are in the sam scope as Dip()
? Does the compiler have to make sure the constructor of x
did already run, or is that your job?
What about z?
如果 Dip 可以访问 tripulate
的本地值和堆栈帧,那么内部原型将是
If Dip gets any access to both the local values of tripulate
and the stack frame, so the internal prototype would be
void Dip(Foo * this, __auto_struct_Dip * stackContext)
{
// ...
}
您基本上复制了结构/类和成员函数的功能,但是在两条不兼容且不可交换的路径上.对于有问题的收益来说,这是非常复杂的.
You have basically replicated the functionality of structs / classes and member functions, but on two incompatible and non-exchangable paths. That's a lot of complexity for a questionable gain.
我曾多次希望使用本地函数,只是因为这会更好地表明需要它的范围.但是所有的问题……还有更多有用的东西可以让 C++ 变得更复杂.
I've wished for local functions a few times, simply because this would better indicate the scope where this is needed. But with all the questions... there are more useful things to throw more complexity onto C++.
使用 C++0x,lambdas 可以做到这一点,允许显式声明它们捕获的内容.
[edit] With C++0x, lambdas can do that, allowing to explicitly state what they capture.
这篇关于为什么不是嵌套函数的想法,在旧的 c++ 标准中实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!