chetzacoalt
chetzacoalt

Reputation: 157

about : Scope of exception object in C++ : why don't I get the copy?

In question about scope of exception it is stated by Aj. that throw and catch clauses will create copies of the exception (unless reference is used I guess)

I tried myself a small toy code and I don't understand the result. here :

//g++  7.4.0
#include <iostream>
using namespace std;
struct Some_error {
    Some_error(float code):err_code(code){ cout << "Some_error(" << err_code << ")\n";  }
    ~Some_error()                        { cout << "~Some_error(" << err_code << ")\n"; }
    Some_error(const Some_error& o):err_code(o.err_code+0.1)      { cout << "Some_error(copy::" << err_code << ")\n";  }
    Some_error(Some_error&& o):err_code(std::move(o.err_code)+.01){ cout << "Some_error(move::" << err_code << ")\n";  }
    int get_code() const { return err_code; }
    private : float err_code;
};

int do_task() { 
    if ( false )  return 42; else throw Some_error {1};
    cout << "end do_task\n" ;
}


void taskmaster(){
    try { auto result = do_task(); cout << "the answer is " << result << "\n" ; }
    catch (Some_error e) { cout << "catch Some_error : " << e.get_code() << "\n" ; }
    cout << "end taskmaster\n" ;
}

int main() { taskmaster(); }

the trace I get is as follows :

Some_error(1)
Some_error(copy::1.1)
catch Some_error : 1
~Some_error(1.1)
~Some_error(1)
end taskmaster

Now first, as I used no reference here, according to Aj., I would expect 2 copies to happen.

And second, there was a copy, that set err_code to 1.1, but the display is still 1.

Remark: just to be complete, I changed the catch to : catch(Some_error& e), and then the trace looks fine to me :

Some_error(1)
catch Some_error : 1
~Some_error(1)
end taskmaster

Upvotes: 0

Views: 46

Answers (1)

Konrad Rudolph
Konrad Rudolph

Reputation: 545508

I would expect 2 copies to happen.

Why? Only one copy is made by the catch block. Where would the second copy happen?

set err_code to 1.1, but the display is still 1.

Because get_code returns an int, so the floating point value gets truncated.

Upvotes: 1

Related Questions