Does rule of not embedding std::string in exceptions still hold with move constructors?

前端 未结 2 1075
挽巷
挽巷 2021-02-05 14:46

I heard some time ago that I should not create exception classes which would have fields of std::string type. That\'s what Boost website says. The rationale is that

2条回答
  •  闹比i
    闹比i (楼主)
    2021-02-05 15:13

    Whether a copy of the string is made when an exception is thrown depends on the catch block.

    Take this example:

    #include 
    
    struct A
    {
    };
    
    void foo()
    {
       throw A();
    }
    
    void test1()
    {
       try
       {
          foo();
       }
       catch (A&& a)
       {
       }
    }
    
    void test2()
    {
       try
       {
          foo();
       }
       catch (A const& a)
       {
       }
    }
    
    void test3()
    {
       try
       {
          foo();
       }
       catch (A a)
       {
       }
    }
    
    int main()
    {
       test1();
       test2();
       test3();
    }
    

    You will not make a copy of A in test1 or test2 but you will end up making a copy in test3.

提交回复
热议问题