POV-Ray : Newsgroups : povray.off-topic : Wikipath : Re: Wikipath Server Time
1 Oct 2024 00:04:29 EDT (-0400)
  Re: Wikipath  
From: Warp
Date: 2 Sep 2008 18:12:29
Message: <48bdba4c@news.povray.org>
Darren New <dne### [at] sanrrcom> wrote:
> What is a "move constructor"? When would you be "moving" some value? If 
> you destructively alter something with aliases, aren't you in trouble? 
> Isn't that what the whole "ownership" concept is supposed to prevent?

  I explained this to you some time ago.

  Suppose you have two 1000x1000 matrices, A and B, and you do this:

Matrix C = A + B;

  The result of operator+ is a nameless temporary which will be destroyed
after the ';'. What that line is doing is initializing C with the value of
that temporary (before it's destroyed).

  What move semantics allow is for the constructor of C to grab the huge
1000x1000 array from the temporary, ie. move it to itself, rather than
copying it (the constructor of C does this by eg. copying the array pointer
from the temporary and assigning null to the pointer in the temporary). When
it has moved the array to itself, the nameless temporary has only a null
pointer, which the destructor of the Matrix class will delete, but deleting
a null pointer is a no-op. Thus nothing is destroyed (except the nameless
temporary Matrix object).

  It's safe for C to do that because it knows that the parameter is a
temporary, nothing points to it, and it's the sole owner of its array.
Nothing will get broken if C just moves the array from the temporary to
itself.

  In the current C++ doing such a move constructor is impossible: There's
no way of knowing if the parameter is a temporary or not.

  What the new C++ standard will add is a way creating a function (eg. a
constructor) which is called when a temporary is given to it as parameter.
This is achieved with the so-called rvalue references. A function taking
an rvalue reference knows that the parameter is a temporary, and thus it's
completely safe to modify it, allowing move semantics to be implemented.

  Move semantics have many useful purposes. For example they make it much
easier to safely return a dynamically allocated object as the return value
of a function, without having to go through the trouble of implementing
reference counting. (The new standard will actually include a one-owner
smart pointer which has move semantics, similar to the current auto_ptr,
but much safer.)

-- 
                                                          - Warp


Post a reply to this message

Copyright 2003-2023 Persistence of Vision Raytracer Pty. Ltd.