Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why must thrown objects be copy-initialized?

Exceptions use the statical type of an object to copy-initialize the thrown object. For instance:

struct foo
{
    foo() = default;
    foo(const foo&) = delete;
};

int main()
{
    throw foo();
}

Clang++ --std=c++14 complains that the explicitly-deleted copy constructor can't be used. Why can't it be move-initialized instead?

like image 667
zneak Avatar asked Oct 13 '15 20:10

zneak


People also ask

Why is it important to make a copy of a passed object in a constructor?

It is necessary to pass object as reference and not by value because if you pass it by value its copy is constructed using the copy constructor. This means the copy constructor would call itself to make copy. This process will go on until the compiler runs out of memory.

Why do we need to initialize object in C++?

A class object with a constructor must be explicitly initialized or have a default constructor. Except for aggregate initialization, explicit initialization using a constructor is the only way to initialize non-static constant and reference class members.

When copy constructor is called object should be created and initialized?

The Copy constructor is called mainly when a new object is created from an existing object, as a copy of the existing object. In C++, a Copy Constructor may be called for the following cases: 1) When an object of the class is returned by value.

Why is object's reference passed to the copy constructor instead of the object itself?

When we create our own copy constructor, we pass an object by reference and we generally pass it as a const reference. One reason for passing const reference is, we should use const in C++ wherever possible so that objects are not accidentally modified.


2 Answers

It can't be move constructed because the type has no move constructor. A deleted copy constructor suppresses the implicit move constructor.

like image 103
Jonathan Wakely Avatar answered Oct 26 '22 05:10

Jonathan Wakely


Modify the code to the following:

struct foo
{
    foo() = default;
    foo(const foo&) = delete;
    foo(foo&&) = default;
};

int main()
{
    throw foo();
}

Read this, the section "Implicitly-declared move constructor".

like image 40
Andrey Nasonov Avatar answered Oct 26 '22 05:10

Andrey Nasonov