In both cases, the vector or list will be grown if necessary to accommodate the new entry. size() will increase by 1, but capacity() may not if the underlying implementation's default allocation size is already big enough to hold the extra element or if you called reserve() with a larger value than the size() before the new element was added.
Ah, but here you are implicitly invoking the MyClass copy constructor because you are passing a MyClass instance as an argument:v.emplace(v.end(), m); // "emplace() constructs a new instance in place" --- I have passed a already constructed element.
Qt Code:
MyClass::MyClass( const MyClass & myClass )To copy to clipboard, switch view to plain text mode
so you end up with two instances, "m" - the one you constructed manually, and a copy of "m", built in place in the vector and initialized with the contents of "m". Even though your class doesn't explicitly define a copy constructor, C++ implements one for you (which by default makes a bitwise copy of the contents of the instance it is initialized with). Likewise for operator=().
To explain in another way:
insert() requires an already-existing instance of the class, which it then makes a copy of into the vector (using MyClass:: operator=( const MyClass & ))
emplace() does not require an existing instance, but creates one for you and initializes it with the extra arguments you pass in (using MyClass:: MyClass( arguments ))
Bookmarks