Here is an exercise from C++ Primer 5th Edition:
Exercise 13.53: As a matter of low-level efficiency, the HasPtr assignment operator is not ideal. Explain why. Implement a copy-assignment and move-assignment operator for HasPtr and compare the operations executed in your new move-assignment operator versus the copy-and-swap version.(P.544)
File hasptr.h
:
//! a class holding a std::string*
class HasPtr
{
friend void swap(HasPtr&, HasPtr&);
friend bool operator <(const HasPtr& lhs, const HasPtr& rhs);
public:
//! default constructor.
HasPtr(const std::string &s = std::string()):
ps(new std::string(s)), i(0)
{ }
//! copy constructor.
HasPtr(const HasPtr& hp) :
ps(new std::string(*hp.ps)), i(hp.i)
{ }
//! move constructor.
HasPtr(HasPtr&& hp) noexcept :
ps(hp.ps), i(hp.i)
{ hp.ps = nullptr; }
//! assignment operator
HasPtr&
operator = (HasPtr rhs);
//! destructor.
~HasPtr()
{
delete ps;
}
private:
std::string *ps;
int i;
};
A part of the file hasptr.cpp
:
//! specific swap.
inline void
swap(HasPtr &lhs, HasPtr &rhs)
{
using std::swap;
swap(lhs.ps, rhs.ps); // swap the pointers, not the string data
swap(lhs.i, rhs.i); // swap the int members
std::cout <<"swapping!\n";
}
//! operator = using specific swap
HasPtr&
HasPtr::operator = (HasPtr rhs)
{
swap(*this,rhs);
return *this;
}
My question is why it is not efficient to do so?
hp = std::move(hp2);
wherehp
andhp2
are objects ofHasPtr
. It did call the move constructor. I think the direction of answering this question should be comparing how many times it call copy and move operations, but not quite sure. – Oribelstd::string
, and the answer is that in 99% of the cases you don't want to do that. But going back to the original question, what would be the effect of assigning an lvalue with a string of the same or smaller length? – Hemispherestd::string
? – Oribelstd::string
dynamically, and it comes at the cost of an additional memory allocation and the pain of having to manage the lifetime. Given that there is no advantage and some disadvantages, I would avoid doing it (I have never encountered that in production code, and I would not accept that in a code review) – Hemisphere