I have a large data set (several gigabytes) stored in a file that does not fit into QVector
(max ~2gb) that is copy-on-write and would not suffer from this. I load the vector into memory like this:
std::vector<int> load()
{
std::vector<int> vec;
QFile file("filename");
file.open(QIODevice::ReadOnly);
QDataStream stream(&file);
stream >> vec; //using my implementation of QDataStream &operator>>(QDataStream &stream, std::vector<int> &v)
return vec;
}
and pass it into this:
class Data
{
public:
Data(const std::vector<int> &data) :
d(data)
{
}
private:
std::vector<int> d;
};
like that:
Data data(load());
Now in load()
the vector is created and filled with data from the file. Then it is returned by value but I believe it should be optimized by the compiler not to actually copy the vec
but rather move it to the destination.
The destination is the private member of Data
but I suspect that the initializer list in the constructor might actually copy the vector rather than moving it as it does not know (or does it?) it has received a const reference to a temporary.
Is there a way to guarantee that the vector will be only moved after construction and not copied in this kind of scenario? I suspect using std::move
, std::forward
or changing signature of the Data::Data()
to take r-value reference?