|
|
|
|
||||||
![]() |
|
|
LinkBack | Outils de la discussion |
|
|
#1 (permalink) |
|
Messages: n/a
Hébergeur: |
Is it possible to throw a reference to a temporary object?
Will the temporary object be copied one or more times? See following example: struct my_exception { my_exception(int i) : i_(i) {} my_exception& ref() {return *this;} int i_; } void f_throws() { throw my_exception(3).ref(); } int main() { try { f_throws(); } catch(my_exception& e) { return e.i_; } return 0; } |
|
|
|
#2 (permalink) |
|
Messages: n/a
Hébergeur: |
Dario Menendez wrote:
> Is it possible to throw a reference to a temporary object? > Will the temporary object be copied one or more times? > > See following example: > > struct my_exception > { > my_exception(int i) : i_(i) {} > my_exception& ref() {return *this;} > int i_; > } > > void f_throws() > { > throw my_exception(3).ref(); > } > > int main() > { > try { > f_throws(); > } > catch(my_exception& e) { return e.i_; } > return 0; > } > I modified your example bit: #include <iostream> struct my_exception { my_exception(int i) : i_(i) { std::cout<<"constr i="<<i<<std::endl;} my_exception(const my_exception &c) { this->i_ = c.i_;std::cout<<"cc"<<std::endl;} const my_exception& ref() { std::cout<<"in ref()"<<std::endl; return *this;} int i_; }; void f_throws() { std::cout<<"throwing"<<std::endl; throw my_exception(3).ref(); //throw my_exception(3); } int main() { try { f_throws(); } catch( const my_exception &e ) { return e.i_; } return 0; } It gave me the answer to your question: one copy. |
|
|
|
#3 (permalink) |
|
Messages: n/a
Hébergeur: |
On Oct 17, 2:25 pm, Dario Menendez <dari...@gmail.com> wrote:
> Is it possible to throw a reference to a temporary object? > Will the temporary object be copied one or more times? > > See following example: > > struct my_exception > { > my_exception(int i) : i_(i) {} > my_exception& ref() {return *this;} > int i_; > > } > > void f_throws() > { > throw my_exception(3).ref(); > > } > > int main() > { > try { > f_throws(); > } > catch(my_exception& e) { return e.i_; } > return 0; > > } 15.1(3) says : "A throw expression initializes a temporary object" Thus, the object to be thrown is always copied, and it is always a 'copy' that is thrown, never the "actual" object associated with the throw clause. [as an aside: the standard allows o get rid of the temporary if doing so doesnot alter the program semantics except for the constructor- destructor execution] try this out - make the teh copy constructor private. The code won't compile anymore. -N |
|
|
|
#4 (permalink) |
|
Messages: n/a
Hébergeur: |
Thanks for the fast answer.
I was looking more for a theoretical guarantee from the language specification about the copying of thrown objects. Maybe compiler implementation details can affect this: optimization could remove that copy or if the exception has to propagate through more than one function call it could be copied more than once. |
|
![]() |
| Outils de la discussion | |
|
|