[petsc-users] passing an object to function

Jed Brown jedbrown at mcs.anl.gov
Sat Oct 8 08:24:55 CDT 2011


On Sat, Oct 8, 2011 at 06:48, Dominik Szczerba <dominik at itis.ethz.ch> wrote:

> If I do so (instead of Vec& that I started with), I receive segfaults.
>

Well now you're doing allocation, so you have to modify the caller's Vec.
This is just pass-by-value semantics.


> An example function:
>
> foo(const Vec& v1, Vec& v2)
> {
>  // allocate v2 and fill it it depending on v1)
>

It would be consistent with PETSc usage to write

foo(Vec v1, Vec *v2)

but in C++, you can also write

foo(Vec v1, Vec &v2)

There is no advantage to passing v1 as Vec& (it's slightly more indirection
and totally unnecessary).


> }
>
> Calling sequence;
>
> Vec v1;
> // create and fill v1;
> Vec v2; // creation expected in foo()
> foo(v1,v2);
> // Now do VecGetArray on v2
>
> This will work as expected only if the signature for foo is Vec&. When
> replaced with Vec I get segfaults on VecGetArray trying to access v2
> after calling foo, suggesting an attempt to access invalid memory
> location.
>

That is because C++ has call-by-value semantics, so v2 in the scope above is
still undefined when you pass it to VecGetArray.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.mcs.anl.gov/pipermail/petsc-users/attachments/20111008/1f2b9e62/attachment.htm>


More information about the petsc-users mailing list