c++ nodiscard

告诉编译器这个函数的返回值不能忽略,会报一个warn,但是谁管warn呢。。。[滑稽]

import <iostream>;
import <string>;

class Person {
public:
  std::string name;
};

class PersonBuilder {
public:
  [[nodiscard("create Person")]]static Person* build(std::string name);
};

Person* PersonBuilder::build(std::string name) {
  Person* p = new Person();
  p->name = name;
  return std::move(p);
}

int main() {
  PersonBuilder::build("hello");
  return 0;
}

main.exe: main.cpp
    g++ main.cpp -o main.exe -std=c++20 -fmodules-ts -xc++-system-header string
D:\code\c\test_nodiscard>make
g++ main.cpp -o main.exe -std=c++20 -fmodules-ts -xc++-system-header string
main.cpp: In function 'int main()':
main.cpp:21:23: warning: ignoring return value of 'static Person* PersonBuilder::build(std::string)', declared with attribute 'nodiscard': 'create Person' [-Wunused-result]
   21 |   PersonBuilder::build("hello");
      |   ~~~~~~~~~~~~~~~~~~~~^~~~~~~~~
main.cpp:14:9: note: declared here
   14 | Person* PersonBuilder::build(std::string name) {
      |         ^~~~~~~~~~~~~
文章目录