2

Can (and maybe should) my coroutine promise class MyCoroutine::Promise have static or non-static initial_suspend and final_suspend methods?

static std::suspend_always initial_suspend() noexcept
{
    return {};
}

static std::suspend_always final_suspend() noexcept
{
    return {};
}

While this works fine (tested with GCC 13), Clang-Tidy complaints "Static member accessed through instance", when using this coroutine type:

MyCoroutine foo() // Clang-Tidy warning here
{
    co_return;
}

This makes sense because "when a coroutine begins execution, it [...] calls promise.initial_suspend()" (see https://en.cppreference.com/w/cpp/language/coroutines.html) via instance, not via promise type.

So should I remove the static keyword from these methods (and make them const)? A this pointer is not required, but probably the compiler can inline and optimize these calls, anyway. Or are static methods a good idea here and is there a better way to deal with this warning?

Some of the examples from https://en.cppreference.com/w/cpp/language/coroutines.html do have static initial_suspend and final_suspend methods, some don't.

1
  • 1
    That's just a bug in clang-tidy. The implicit call to initial_suspend inserted by the compiler should not be triggering style criticisms like that. Commented Aug 25 at 22:11

1 Answer 1

4

Making them static would change nothing meaningful about the program. Non-static, non-virtual members don't have any inherent limitations to compiler-based optimizations compared to static ones. If the function definitions are in the header/module interface, then the compiler can inline them or otherwise do definition-based optimizations regardless of whether they're static or not.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, Nicol. So you would prefer non-static methods, while Brian seems to prefer static ones. I guess both is alright.
I thought he just said that it shouldn't be a warning. That's not expressing that he "prefers static ones". Personally, I don't see the point of the "static member accessed through instance" warning in any cases.
You are right. And I tend to make these methods non-static now, although Clang-Tidy might give another warning (see clang.llvm.org/extra/clang-tidy/checks/readability/…, I haven't tested it in this case, though). While the this pointer is not used (at least not now), logically these methods belong to the instance, not the type.

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.