On 5/8/2015 12:30 PM, Doug Mika wrote:
> I have the following implementation of a move constructor: (it
> assumes
our string class has a char* buf, and int len (char length) as members)
>
> String::String(String&& other) //the canonical signature of a move constructor
> //first, set the target members to their default values
> : buf(nullptr)
This is unnecessary if you're writing into it pretty much right away...
> , len(0)
Same here.
> {
> std::cout << "In String's move constructor. length = "
> <<other.len << "." << std::endl;
>
> //next, pilfer the source's resources
> buf=other.buf;
> len=other.len;
It's actually better to initialize *than* assign to. Read the FAQ, I
think there was something like "prefer initialization over assignment"
section, but I can be mistaken.
> //finally, set the source's data members to default values to prevent aliasing
> other.buf = nullptr;
> other.len=0;
> }
Generally speaking with the implied declaration of 'String' class, you
need to do
String::String(String&& other)
: buf(other.buf)
, len(other.len)
{
other.buf = nullptr;
other.len = 0;
}
>
> Shouldn't we delete the this->buf pointer before we set it to
> nullptr?
Or does buf(nullptr) automatically delete what the objects this->buf
points to?
See floyd's reply.
V
--
I do not respond to top-posted replies, please don't ask