#include <iostream>
#include <memory>
class A
{
public:
static [[nodiscard]] std::unique_ptr<A> create();
virtual int get_version() = 0;
virtual ~A() = default;
};
class B : public A
{
public:
[[nodiscard]] int get_version() override
{
return 20;
}
};
std::unique_ptr<A>
A::create()
{
return std::make_unique<B>();
}
int main()
{
auto a = A::create();
[[maybe_unused]] int v = a->get_version();
}
I tried to use [[nodiscard]]
to not allow ignoring the return value of A::create()
.
But, I get different compilation output in GCC and Clang.
Tried with
- GCC: 8.5
- Clang: 15.0.0
- Compilation options: -O3 -std=c++17
- Godbolt link: https://godbolt.org/z/qa7TfcK9f
GCC:
<source>:7:12: warning: attribute ignored [-Wattributes]
static [[nodiscard]] std::unique_ptr<A> create();
^
<source>:7:12: note: an attribute that appertains to a type-specifier is ignored
ASM generation compiler returned: 0
<source>:7:12: warning: attribute ignored [-Wattributes]
static [[nodiscard]] std::unique_ptr<A> create();
^
<source>:7:12: note: an attribute that appertains to a type-specifier is ignored
Execution build compiler returned: 0
Program returned: 0
Clang:
<source>:7:14: error: 'nodiscard' attribute cannot be applied to types
static [[nodiscard]] std::unique_ptr<A> create();
^
1 error generated.
ASM generation compiler returned: 1
<source>:7:14: error: 'nodiscard' attribute cannot be applied to types
static [[nodiscard]] std::unique_ptr<A> create();
^
1 error generated.
Execution build compiler returned: 1
Am I doing something wrong? And why does these compilers have different behavior?
This code works with MSVC v19.33 properly without any errors or warnings: https://godbolt.org/z/dWsv4jTo5