【发布时间】:2018-08-30 00:31:53
【问题描述】:
我有几个 c++ 程序都使用函数捕获。其中一个成功退出代码0,但另一个导致Segmentation fault 错误。 std::shared_ptr<std::string>() 是通过引用捕获的,应该在调用 lambda 之前销毁。如果是这样,那为什么我的第一个程序以成功结束,而第二个却没有呢?
成功的计划
#include <string>
#include <memory>
#include <iostream>
#include <functional>
std::function<void()> lambda;
void assign_closure() {
std::shared_ptr<std::string> ptr = std::make_shared<std::string>("nope");
lambda = [&ptr]() {
std::cout << "Trying to print this should segault: " << *ptr << std::endl;
};
}
int main(int, char*[]) {
assign_closure();
lambda();
return 0;
}
计划失败
#include <string>
#include <memory>
#include <iostream>
#include <functional>
std::function<void()> lambda;
void assign_closure() {
std::shared_ptr<std::string> ptr = std::make_shared<std::string>("nope");
lambda = [&ptr]() {
std::cout << "Trying to print this should segault: " << *ptr << std::endl;
};
}
void do_some_work() {
std::cout << "doing some work" << std::endl;
}
int main(int, char*[]) {
assign_closure();
do_some_work();
lambda();
return 0;
}
是否有一个编译器标志可以用来发现悬空引用?
【问题讨论】:
-
“成功程序”也是UB
标签: c++ reference functional-programming shared-ptr capture