<div class="gmail_quote">On Sat, Oct 8, 2011 at 06:48, Dominik Szczerba <span dir="ltr"><<a href="mailto:dominik@itis.ethz.ch">dominik@itis.ethz.ch</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">
<div id=":f8">If I do so (instead of Vec& that I started with), I receive segfaults.<br></div></blockquote><div><br></div><div>Well now you're doing allocation, so you have to modify the caller's Vec. This is just pass-by-value semantics.</div>
<div> </div><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;"><div id=":f8">
An example function:<br>
<br>
foo(const Vec& v1, Vec& v2)<br>
{<br>
// allocate v2 and fill it it depending on v1)<br></div></blockquote><div><br></div><div>It would be consistent with PETSc usage to write</div><div><br></div><div>foo(Vec v1, Vec *v2)</div><div><br></div><div>but in C++, you can also write</div>
<div><br></div><div>foo(Vec v1, Vec &v2)</div><div><br></div><div>There is no advantage to passing v1 as Vec& (it's slightly more indirection and totally unnecessary).</div><div> </div><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">
<div id=":f8">
}<br>
<br>
Calling sequence;<br>
<br>
Vec v1;<br>
// create and fill v1;<br>
Vec v2; // creation expected in foo()<br>
foo(v1,v2);<br>
// Now do VecGetArray on v2<br>
<br>
This will work as expected only if the signature for foo is Vec&. When<br>
replaced with Vec I get segfaults on VecGetArray trying to access v2<br>
after calling foo, suggesting an attempt to access invalid memory<br>
location.</div></blockquote></div><br><div>That is because C++ has call-by-value semantics, so v2 in the scope above is still undefined when you pass it to VecGetArray.</div>