2

I have a function named return_local where it returns an instance of a local class enclosed with a lambda.

auto return_local() {
  return [] {
    static int sample { 5 };
    struct Point {
      int x, y;
      int show_sample() { return sample; }
    };
    return Point {};
  }();
}
using Point = decltype(return_local());

Now, I can use Point as alias with characteristics of local classes.

Point p {.x = 4, .y = 1};
p.show_sample(); // returns 5

Is this code normal? Are there any benefits of using this "leaked" class?

3
  • 3
    You can do that, but it's not clear why you would want to. Why not just define Point at namespace scope? Commented Jul 25, 2021 at 3:30
  • 2
    It's a bit unusual, but the code is within the bounds of what I'd consider normal. I don't see any benefits to coding this way over declaring Point on its own and having the sample be a class static variable. The downside, as I see it, is it is more cognitive load for maintenance. Commented Jul 25, 2021 at 3:30
  • 3
    This is sometimes called a "Voldemort Type" (A type that shall not be named). Commented Jul 25, 2021 at 3:57

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.