[Trilinos-Users] Teuchos::RCP Call by reference
Hoemmen, Mark
mhoemme at sandia.gov
Thu Aug 8 17:35:46 MDT 2013
On Aug 8, 2013, at 12:00 PM, <trilinos-users-request at software.sandia.gov>
<trilinos-users-request at software.sandia.gov> wrote:
> Message: 1
> Date: Fri, 9 Aug 2013 00:38:34 +0900
> From: "Sunghwan Choi" <iomn159753 at kaist.ac.kr>
> Subject: [Trilinos-Users] Teucho::RCP Call by reference
> To: trilinos-users at software.sandia.gov
> Message-ID: <1b9a01ce944d$58b45910$0a1d0b30$@kaist.ac.kr>
> Content-Type: text/plain; charset="us-ascii"
>
> Dear all,
>
> Hi I met a weird situation. I computed scaling of Epetra_MultiVector in a
> function and I got it through 'call by reference' I check the Scale does do
> its work but outside of function the value was not changed. I wrote pseudo
> code
>
>
>
> int func(Teuchos::RCP<Epetra_MultiVector>
> before_values,Teuchos::RCP<Epetra_MultiVector> after_values){
>
> after_values = Teuchos::rcp(new Epetra_MultiVector(*before_values) );
>
> double scaling = 0.5;
>
> cout <<"before values" <<endl;
>
> cout << *after_values <<endl;
>
> after_values->Scale(1.0/scaling) ;
>
> cout <<"after values" <<endl;
>
> cout << *after_values<<endl;
>
> return;
>
> }
>
>
>
> This is super simple code but I don't know why it is not working. In other
> part of my code, I used call-by-reference using Teuchos::RCP but this is not
> working. Do you have any idea on this situation?
This is not "call by reference"; this is "call by pointer." Imagine replacing the RCP with a raw pointer, like this:
int
func (Epetra_MultiVector* before_values,
Epetra_MultiVector* after_values)
{
after_values = new Epetra_MultiVector (*before_values);
double scaling = 0.5;
after_values->Scale (1.0 / scaling);
return 0; // your function returns int
}
This function would have the same problem as your function above (in addition to the problem of leaking memory). (The only difference between an RCP and a raw pointer is that RCP handles deallocation safely.) If you want to change the _pointer_, you either need to pass in the RCP _itself_ by nonconst reference ("RCP<Epetra_MultiVector>&"), or you need to return the RCP. I recommend the latter. I also recommend passing before_values by const reference, since the function doesn't need to keep it:
RCP<Epetra_MultiVector>
func (const Epetra_MultiVector& before_values)
{
RCP<Epetra_MultiVector> after_values = rcp (new Epetra_MultiVector (before_values));
double scaling = 0.5;
after_values->Scale (1.0 / scaling);
return after_values;
}
mfh
More information about the Trilinos-Users
mailing list