On Sunday, 7 August 2016 16:21:16 UTC+3, fl wrote:
> Hi,
>
> When I read the following snippet on move function in a class, I am curious
> about:
>
> delete ptr;
What book you use for learning C++?
Delete expression destructs object(s) previously allocated by the new
expression and releases obtained memory area. The object destructed and
memory area released are pointed at by that 'ptr'.
>
> in the move assignment. After this deletion, it assigns a new pointer value:
>
> ptr = x.ptr;
Yes since the value of 'ptr' did become invalid (pointing at destructed and
released memory).
>
> What is deleted? I see a pointer is deleted, then it assigns a new pointer
> value. Could you explain it to me?
>
If 'ptr' is raw pointer to 'std::string' like it seems to be in code below
then it is awful example. The 'std::string' itself is made to get rid of
ad nauseum management of memory pointed at by raw pointer to 'char' and
already manages everything perfectly what is needed. Doing 'new string'
is inefficient and error-prone manual over-management and bloat of code.
>
> class Example6 {
> string* ptr;
> public:
> Example6 (const string& str) : ptr(new string(str)) {}
> ~Example6 () {delete ptr;}
> // move constructor
> Example6 (Example6&& x) : ptr(x.ptr) {x.ptr=nullptr;}
> // move assignment
> Example6& operator= (Example6&& x) {
> delete ptr;
> ptr = x.ptr;
> x.ptr=nullptr;
> return *this;
> }
> // access content:
> const string& content() const {return *ptr;}
> // addition:
> Example6 operator+(const Example6& rhs) {
> return Example6(content()+rhs.content());
> }
> };
Lot shorter cleaner and more efficient that does same:
class RealExample6
{
std::string str_;
public:
explicit RealExample6(std::string const& str)
: str_(str)
{}
// access content:
std::string const& content() const {return str_;}
// make 'operator+=' as public member and 'operator+' as nonmember
RealExample6& operator+=(RealExample6 const& that)
{
str_ += that.str_;
return *this;
}
};
RealExample6 operator+(RealExample6 lhs, Realexample6 const& rhs)
{
return lhs += rhs;
}