Search code examples
c++c++11copy-constructornoexcept

Is make_unique in initializer list in copy constructor good purpose to not use noexcept specifier?


I have a hurdle with noexcept specifier next to my copy constructor.

#include <memory>
#include <vector>

class Foo final {
 public:
  Foo() noexcept = default;
  Foo(const Foo& oth) : impl_(std::make_unique<Foo::Impl>()) {} // <---
  ~Foo() noexcept = default;

private:
  class Impl;
  std::unique_ptr<Impl> impl_;
};

class Foo::Impl {
  ...
 private:
  std::vector<int> some_data;
}

I'm not sure if I should put noexcept next to copy constructor while there is std::make_unique that can throw bad_alloc.

Any help will be apreciated!


Solution

  • The cpp coding guidelines are pretty clear about it in E.12: Use noexcept when exiting a function because of a throw is impossible or unacceptable

    So you can use noexcept even if the call of that function/ctor could result in an exception, if that exception would - in your opinion - result in a not handleable state of your application.

    Example from the guidelines:

    vector<double> munge(const vector<double>& v) noexcept
    {
        vector<double> v2(v.size());
        // ... do something ...
    }
    

    The noexcept here states that I am not willing or able to handle the situation where I cannot construct the local vector. That is, I consider memory exhaustion a serious design error (on par with hardware failures) so that I'm willing to crash the program if it happens.

    So if a failed construction of Foo can be handled using a try-catch block without serious problems. Then you won't use a noexcept there.