Exception and Copy Constructor : C++

前端 未结 2 2030
无人共我
无人共我 2021-01-11 16:12

Referring to http://en.wikipedia.org/wiki/Copy_elision

I run below code:

#include 

struct C {
  C() {}
  C(const C&) { std::cout         


        
2条回答
  •  半阙折子戏
    2021-01-11 16:32

    Copy & Move constructor while throwing user-defined type object

    struct demo
    {
        demo() = default;
        demo(demo &&) = delete;
        demo(const demo &) = delete;
    };
    
    int main()
    {
        throw demo{};
        return 0;
    }
    
    • Upon throw expression, a copy of the exception object always needs to be created as the original object goes out of the scope during the stack unwinding process.
    • During that initialization, we may expect copy elision (see this) – omits copy or move constructors (object constructed directly into the storage of the target object).
    • But even though copy elision may or may not be applied you should provide proper copy constructor and/or move constructor which is what C++ standard mandates(see 15.1). See below compilation error for reference.
    error: call to deleted constructor of 'demo'
        throw demo{};
              ^~~~~~
    note: 'demo' has been explicitly marked deleted here
        demo(demo &&) = delete;
        ^
    1 error generated.
    compiler exit status 1
    
    • If we catch an exception by value, we may also expect copy elision(compilers are permitted to do so, but it is not mandatory). The exception object is an lvalue argument when initializing catch clause parameters.

    From: 7 best practices for exception handling in C++

提交回复
热议问题