This is the mail archive of the
libstdc++@gcc.gnu.org
mailing list for the libstdc++ project.
std::vector<T> does not use the move constructor of T to change its capacity
- From: Jakub Galgonek <jakub dot galgonek at gmail dot com>
- To: libstdc++ at gcc dot gnu dot org
- Date: Fri, 16 Jan 2015 08:05:18 +0100
- Subject: std::vector<T> does not use the move constructor of T to change its capacity
- Authentication-results: sourceware.org; auth=none
Hi,
I have made some experiments with move constructors in C++ 11 (in g++
4.8.3 and g++ 4.9.2) and I have observed that std::vector<T> uses the
copy constructor (instead of the move constructor) of T to change the
capacity of a vector instance.
For example, the following code:
#include <iostream>
#include <vector>
class Test {
public:
Test() { }
Test(const Test &ins) { std::cout << "copy constructor" << std::endl; }
Test(const Test &&ins) { std::cout << "move constructor" << std::endl; }
};
int main() {
Test t1, t2, t3;
std::vector<Test> vector;
std::cout << "-----" << std::endl;
vector.push_back(std::move(t1));
std::cout << "-----" << std::endl;
vector.push_back(std::move(t2));
std::cout << "-----" << std::endl;
vector.push_back(std::move(t3));
std::cout << "-----" << std::endl;
vector.reserve(10);
std::cout << "-----" << std::endl;
return 0;
}
produces the following output:
-----
move constructor
-----
move constructor
copy constructor
-----
move constructor
copy constructor
copy constructor
-----
copy constructor
copy constructor
copy constructor
-----
On the other hand, if the copy constructor is deleted, than the move
constructor is used to change the capacity. Also note that Visual
Studio 2013 uses only move constructors in the both cases.
Is this a gcc bug or is there some reason for this behaviour?
Thanks,
Jakub