2010-09-01 141 views
8

这样的关闭实现有没有问题(从python黑客窃取)?C++关闭破解

void function(int value) { 
    struct closure { 
     closure(int v = value) : value_(value) {} 
     private: int value_; 
    }; 
    closure c; 
} 

经过进一步调查,出现在成员函数中,局部变量不能用作默认值,但是对象变量可以。

+0

这是大多数其他语言在幕后捕获具有本地函数的局部变量时所做的。例如,使用匿名代理和捕获的变量反编译C#代码。 – 2010-09-01 00:25:51

+2

您需要明确地将值传递给构造函数:函数的默认参数不能是局部变量。该规则适用于_all_函数,而不仅仅是成员函数。 – 2010-09-01 00:35:17

+0

@詹姆斯,谢谢我不知道规则很好 – Anycorn 2010-09-01 00:37:33

回答

6

这看起来是一个关闭的好基础。更多的是一种成语,而不是黑客,因为你正在使用语言功能来达到他们的预期目的。

当然,你的例子没有做任何事情。它只能在function之内使用。

无端的C++ 0x插头:

#include <functional> 

void some_function(int x) { } 

void function(int value) { 
    struct closure { 
     std::function< void() > operator()(int value) 
      { return [=](){ some_function(value); }; } 
    }; 

    auto a = closure()(value); 
    auto b = closure()(5); 

    a(); 
    b(); 
    b(); 
} 
+0

对,我刚刚发布了简短的示例给出的想法 – Anycorn 2010-09-01 00:23:06

+0

其中一个月,我想我需要开始使用0x – Anycorn 2010-09-01 00:39:47

6

封闭的C++当量:

class Closure 
{ 
    public: 
     Closure(std::string const& g) 
      :greet(g) 
     {} 
     void operator()(std::string const& g2) 
     { 
      std::cout << greet << " " << g2; 
     } 
    private: 
     std::string greet; 
}; 

int main() 
{ 
    Closure c("Hello"); 

    c("World"); // C acts like a function with state. Whooo. 
} 

随着C++ 11新lambda语法变得更容易。

int main() 
{ 
    std::string g("Hello"); 

    auto c = [g](std::string const& m) {std::cout << g << " " << m;}; 

    c("World"); 
} 

使用C++ 14中的新扩展lambda语法(gcc上的-std = C++ 1y),它变得更加容易。

int main() 
{ 
    auto c = [g="Hello"](std::string const& m) {std::cout << g << " " << m;}; 

    c("World"); 
} 
+0

伟大的易于得到的例子,(+) – Wolf 2014-09-25 10:27:46

+0

@Wolf:用C++ 11更新 – 2014-09-25 18:41:13