Suppose I have the following code:
#include <iostream>
#include <vector>
using namespace std;
class X {
public:
int x[1000];
X(int y) { for (int i = 0; i < 1000; i++) x[i] = y; }
};
int main() {
vector<X> v;
X x0(0);
X x1(1);
X x2(2);
v.push_back(x0);
v.push_back(x1);
v.push_back(x2);
cout << v[2].x[33] << endl;
return 0;
}
If I understand correctly, in my code, I am allocating memory on the stack for x0
, x1
and x2
, then copying those contents onto memory allocated for me by vector
. Furthermore, as far as I understand, move semantics can't help here because it's not exactly like X
is holding a pointer to resource located somewhere else.
Is it possible for me to directly call the constructor on the raw memory block allocated for me by vector
? If not, what would be the proper way to handle situations like these?
You need to use C++11's emplace_back
.
http://en.cppreference.com/w/cpp/container/vector/emplace_back
Also, if you're concerned about excess copies/moves, try starting with v.reserve(3)
.
You can also use std::ref
or boost::ref
if available and store a reference of the object in the vector, thus avoiding the copy.
#include <iostream>
#include <vector>
#include <functional>
using namespace std;
class X {
public:
int x[1000];
X(int y) { for (int i = 0; i < 1000; i++) x[i] = y; }
};
int main() {
std::vector<std::reference_wrapper<X> > v;
X x0(0);
X x1(1);
X x2(2);
v.push_back(std::ref(x0));
v.push_back(std::ref(x1));
v.push_back(std::ref(x2));
cout << v[2].get().x[33] << endl;
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With