简体   繁体   English

扩展变量的 scope 以用于 c++ 中的 lambda 的最佳方法是什么?

[英]What's the best way to extend the scope of a variable for use in a lambda in c++?

I have class:我有 class:

class MyFunctionRunner{
  public:
      static callFunc(){
         func_(); //Calls the function that's set
      }
      static setFunc(std::function<void()> func){
         func_ = func; //Sets a function
      }
 private:
     static std::function<void()> func_;
 }

And a function:还有一个 function:

void MyFunc(const std::string& a,const std::string& b){
   MyClass myObj{};

   MyFunctionRunner::setFunc(
     [&myObj](){
        myObj.setA(a); 
        myObj.setB(b);
   }); //Passes in a lambda function as a parameter that captures `myObj` as reference. 
 }

In my main, I have:在我的主要,我有:

myFunc("a","b");
MyFunctionRunner::callFunc();

This compiles fine but hits a runtime error of "stack-use-after-return" because I guess it's by the time I run the function, myObj is out of scope?这编译得很好,但会遇到“stack-use-after-return”的运行时错误,因为我猜是在我运行 function 时, myObj已经超出 scope? What can I do to extend the scope/lifetime of myObj reference?我可以做些什么来延长myObj参考的范围/生命周期? Assume that MyClass 's implementation (out of my control) has prevented copy constructor ("copy constructor is implicitly deleted...")假设MyClass的实现(我无法控制)阻止了复制构造函数(“复制构造函数被隐式删除......”)

You can't extend the scope of the myObj variable without moving it into global/static memory.如果不将myObj变量的 scope 移动到全局/静态 memory 中,则无法扩展它。 But what you can do instead is create the MyClass object in dynamic memory and change myObj to be a pointer to that object, and then you can capture a copy of that pointer in the lambda, eg: But what you can do instead is create the MyClass object in dynamic memory and change myObj to be a pointer to that object, and then you can capture a copy of that pointer in the lambda, eg:

void MyFunc(const std::string& a,const std::string& b){
   MyClass *myObj = new MyClass;

   MyFunctionRunner::setFunc(
     [myObj](){
        myObj->setA(a); 
        myObj->setB(b);
        delete myObj;
   });
}

In which case, you should consider using a smart pointer for safer memory management, eg:在这种情况下,您应该考虑使用智能指针来进行更安全的 memory 管理,例如:

void MyFunc(const std::string& a,const std::string& b){
   auto myObj = std::make_shared<MyClass>();

   MyFunctionRunner::setFunc(
     [myObj](){
        myObj->setA(a); 
        myObj->setB(b);
   });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM