[petsc-users] question about the PETSc Vec object and C++ destructors
Matthew Knepley
knepley at gmail.com
Wed Feb 5 21:14:10 CST 2014
On Wed, Feb 5, 2014 at 8:02 PM, David Liu <daveliu at mit.edu> wrote:
> Hi, this is a question mainly to clear up my understanding of what the Vec
> object is. Consider the following C++ code:
>
> //=========================
>
> #include <petsc.h>
>
>
> class thing{
>
> public:
> Vec x;
> thing(){};
> thing(int N){
> PetscPrintf(PETSC_COMM_WORLD, "x before create = %i\n", x);
> VecCreateSeq(PETSC_COMM_SELF, N, &x);
> PetscPrintf(PETSC_COMM_WORLD, "x after create = %i\n", x);
> }
> ~thing(){
> PetscPrintf(PETSC_COMM_WORLD, "x before destroy = %i\n", x);
> VecDestroy(&x);
> PetscPrintf(PETSC_COMM_WORLD, "x after destroy = %i\n", x);
> }
> };
>
>
> int main(int argc, char** argv){
>
> PetscInitialize(&argc, &argv, PETSC_NULL, PETSC_NULL);
>
> thing t;
> PetscPrintf(PETSC_COMM_WORLD, "x before everything = %i\n", t.x);
> t = thing(2);
> PetscPrintf(PETSC_COMM_WORLD, "x after everything = %i\n", t.x);
> PetscFinalize();
> }
>
> //=========================
>
> The output, when run sequentially, is
>
> x before everything = 0
> x before create = 0
> x after create = -326926224
> x before destroy = -326926224
> x after destroy = 0
> x after everything = -326926224
>
> (among some unimportant error messages). If I try to VecGetSize(t.x, &N),
> immediately after the line "t = thing(2)", I get an error indicating that
> t.x has been destroyed.
>
> This behavior, as well as the printed output, suggests that the destructor
> being called during the line "t = thing(2)" is destroying the Vec just
> created by "thing(2)". Shouldn't it be destroying the Vec declared by the
> very first "thing t", and hence throwing an error saying that you can't
> destroy a v that has not been created?
>
This has nothing to do with Vec, it is about C++ copy semantics. This is
why I would
never tell someone to use C++.
Matt
--
What most experimenters take for granted before they begin their
experiments is infinitely more interesting than any results to which their
experiments lead.
-- Norbert Wiener
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.mcs.anl.gov/pipermail/petsc-users/attachments/20140205/3dce16e5/attachment.html>
More information about the petsc-users
mailing list