Afficher un message
Vieux 17/10/2007, 10h53   #2
anon
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: Throwing a reference to a temporary object

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.
  Réponse avec citation
 
Page generated in 0,04996 seconds with 9 queries