In my example, an object Bar
is created in a lambda. The Foo
class calls this lambda and obtains ownership of the returned Bar
object. At the same time within the lambda, I use a reference capture to get the raw pointer of the Bar
object created in the lambda.
If I were to make a method call on this raw pointer p->DoSomething
, I expect it to segfault because Foo
which owns the created Bar
object is automatically destroyed since it has gone out of scope.
However, this code runs fine and prints "Do Something". Is this a case where I got "lucky" and is undefined behavior?
Example code:
class Bar { public: Bar(){} void DoSomething() { std::cout << "DO SOMETHING" << std::endl; } }; class Foo { std::unique_ptr<Bar> bar_; public: Foo(std::function<std::unique_ptr<Bar>()> fn) { std::unique_ptr<Bar> r = fn(); // variable r should go out of scope and is destroyed. } }; class Test { Bar* p; public: Test() { auto foo = std::make_unique<Foo>([this](){ auto bar = std::make_unique<Bar>(); p = bar.get(); return bar; }); p->DoSomething(); // Should this work or is undefined behaviour } }; int main() { auto t = new Test(); }
https://stackoverflow.com/questions/66937450/is-this-an-example-of-dangling-pointer-undefined-behavior-or-is-normal-behavio April 04, 2021 at 10:10AM
没有评论:
发表评论