Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to prevent calling the constructor without assigning it to a variable?

i.e. this should be ok:

Object obj("param");

but this should not:

Object("param");

Is there a way to prevent the second scenario from being done?

like image 584
sberfiacreix Avatar asked Oct 15 '25 10:10

sberfiacreix


1 Answers

You can use the nodiscard attribute for a type (with C++17 or later).

struct [[nodiscard]] Object {};

auto main() -> int {
  Object{}; // error
  return 0;
}
like image 156
local-ninja Avatar answered Oct 17 '25 22:10

local-ninja



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!