Re: Throwing a reference to a temporary object
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
|