CyberShadow
  • CyberShadow
Question about move constructors in C++
Computer Science
  • Stacey Warren - Expert brainly.com
Hey! We 've verified this expert answer for you, click below to unlock the details :)
SOLVED
At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.
katieb
  • katieb
I got my questions answered at brainly.com in under 10 minutes. Go to brainly.com now for free help!
CyberShadow
  • CyberShadow
This is how we define a normal move constructor: string(string&& move) // string&& is an rvalue reference to a string { data = move.data; move.data = nullptr; //What's the need of this?? } My question is , why do we need to call "move.data=nullptr;"? Why do we need to leave it in a safe state if it's a rvalue and never going to be used again?Why can't we just leave it as it is?
Curry
  • Curry
Well since it's a constructor, I believe you probably won't be popping it off the stack? That being said, even if you're never using it again, you will get memory leaks in the code when it's not set to null. memory leaks can be very bad if not dealt with. They can cause segmentation faults often, and leave security bugs in your code.
anonymous
  • anonymous
the reason you set the other to null is so you don't end up with two separate mutable strings using same underlying data, as otherwise you end up risking corruption

Looking for something else?

Not the answer you are looking for? Search for more explanations.

More answers

CyberShadow
  • CyberShadow
Yeah i think i got it.. The main point of a move constructor is to steal the data from the owner, while without the nullptr call , its just sharing the data instead of stealing..... also it can lead to memory leaks.
anonymous
  • anonymous
eh, in practice It's hardly going to lead to a memory leak -- it's a lot more likely the pointer would get freed when the original object falls out of scope or is otherwise destroyed, and you'd end up with invalid state when your string suddenly starts accessing reclaimed garbage memory
CyberShadow
  • CyberShadow
You are right @oldrin.bataku , I tested the above code without setting "move.data = nullptr" and move object's destructor gets called when it went out of scope and then we are left with dangling pointer data.

Looking for something else?

Not the answer you are looking for? Search for more explanations.