Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#ccccff
langcpp

Widget w( /* constructor arguments */);

...

Code Block
bgColor#ffcccc
langcpp

Widget w = Widget( /* constructor arguments */);

...

Code Block
bgColor#ffcccc
langcpp

Widget w = /* constructor argument */;

Besides being inefficient, this last syntax violates OOP32OOP09-CPP. Ensure that single-argument constructors are marked "explicit".

...

Code Block
bgColor#FFCCCC
langcpp

class Widget {
public:
  explicit Widget() {cerr << "constructed" << endl;}
};

int main() {
  Widget w();
  return 0;
}

...

Code Block
bgColor#ccccff
langcpp

class Widget {
public:
  explicit Widget() {cerr << "constructed" << endl;}
};

int main() {
  Widget w;
  return 0;
}

...

Code Block
bgColor#FFCCCC
langcpp

class Widget {
public:
  explicit Widget(int in) : i(in) {cerr << "widget constructed" << endl;}
private:
  int i;
};

class Gadget {
public:
  explicit Gadget(Widget wid) : w(wid) {cerr << "gadget constructed" << endl;}
private:
  Widget w;
};

int main() {
  int i = 3;
  Gadget g(Widget(i));
  cout << i << endl;
  return 0;
}

...

Code Block
bgColor#ccccff
langcpp

Gadget g(Widget i);

As a result, this program compiles cleanly and prints only 3 as output, because no Gadget or Widget is constructed.

...

Code Block
bgColor#ccccff
langcpp

int main() {
  int i = 3;
  Widget w(i);
  Gadget g(w);
  cout << i << endl;
  return 0;
}

...

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

OOP31-CPP

low

likely

low

P9

L2

Automated Detection

Tool

Version

Checker

Description

 PRQA QA-C++

 
Include Page
PRQA QA-C++_v
PRQA QA-C++_v

2510

 

 

Bibliography

  • [Meyers 01] Item 6: Be alert for C++'s most vexing parse.

...