Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Move Constructors

25 views
Skip to first unread message

Doug Mika

unread,
May 8, 2015, 12:31:08 PM5/8/15
to
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)
, len(0)
{
std::cout << "In String's move constructor. length = "
<<other.len << "." << std::endl;

//next, pilfer the source's resources
buf=other.buf;
len=other.len;
//finally, set the source's data members to default values to prevent aliasing
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?

red floyd

unread,
May 8, 2015, 12:41:45 PM5/8/15
to
Why? We're *CREATING* "this". Therefore its buf pointer didn't point
to anything.


Victor Bazarov

unread,
May 8, 2015, 1:00:15 PM5/8/15
to
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
0 new messages