On 5/8/2015 11:51 AM, Doug Mika wrote:
> Here I have another two short extracts from a document I was reading. The first is:
>
> vector<String> vs;
> String s(15);
> vs.push_back(s); //uses String's copy constructor
>
> does this use String's copy constructor because it uses the void
push_back (const value_type& val); method which inside of it copies the
string passed as reference into the vector vs?
Yes.
> Also, here is another short code extract:
>
> vector<String> vs;
> String s1(15), s2(20);
> vs.push_back(static_cast<String&&>(s1)); //uses String's move constructor
> vs.push_back(std::move(s2)); //uses String's move constructor
>
> Does this use String's move constructor because inside the
> overwritten push_back method which is void push_back (value_type&&
> val); the method inside guarantees the implementation of the string's
> move constructor and not the copy constructor?
Too many words for me to understand, honestly. "The method inside
guarantees.."? There are two overloaded 'push_back' member functions,
one takes a prvalue (a ref to const lvalue) just like it did in 1998,
and the other that takes an xvalue (an rvalue ref), which is new in
C++11. *Both* create the element by constructing it, so essentially
their code ought to be identical. However, due to the existence of
overloaded constructors in the element type (std::string in this case),
the two 'push_back' functions will use different c-tors, the copy c-tor
in the case of the old 'push_back' and the move c-tor in the case of the
newer 'push_back'.
V
--
I do not respond to top-posted replies, please don't ask