Quantcast
Channel: When should I really use noexcept? - Stack Overflow
Viewing all articles
Browse latest Browse all 10

Answer by drbombe for When should I really use noexcept?

$
0
0

Here is a simple example to illustrate when it could really matter.

#include <iostream>#include <vector>using namespace std;class A{ public:  A(int){cout << "A(int)" << endl;}  A(const A&){cout << "A(const A&)" << endl;}  A(const A&&) noexcept {cout << "A(const A&&)" << endl;}  ~A(){cout << "~S()" << endl;}};int main() {  vector<A> a;  cout << a.capacity() << endl;  a.emplace_back(1);  cout << a.capacity() << endl;  a.emplace_back(2);  cout << a.capacity() << endl;  return 0;}

Here is the output

0A(int)1A(int)A(const A&&)~S()2~S()~S()

If we remove the noexcept in the move constructor, here is the output

0A(int)1A(int)A(const A&)~S()2~S()~S()

The key difference is A(const A&&) vs A(const A&&). In the second case, it has to copy all the values using the copy constructor. VERY INEFFICIENT!!


Viewing all articles
Browse latest Browse all 10

Latest Images

Trending Articles





Latest Images