I'm implementing a factory class which builds a vector of uint8_t. I want to be able to utilize move semantics when returning the resulting vector. This seems to work but I'm not confident this is the correct way of accomplishing what I want.
I have seen quite a few examples of how a returned automatic variable will be regarded as an rvalue and use the move constructor of the calling code, but in my example, the returned object is a member. I know the member will loose its contents if the caller puts the return value into a move constructor - and this is just what I want.
I have written it something like this:
#include <cstdint>
#include <iostream>
#include <vector>
class Factory
{
public:
std::vector<uint8_t> _data;
Factory(std::size_t size) :
_data(size, 0)
{
}
void buildContent(int param)
{
// perform operations on the contents of _data
}
std::vector<uint8_t> && data()
{
return std::move(_data);
}
};
int main()
{
Factory factory(42);
factory.buildContent(1);
std::vector<uint8_t> temp(factory.data());
std::cout << "temp has " << temp.size() << " elements" << std::endl;
std::cout << "factory._data has " << factory._data.size() << " elements" << std::endl;
return 0;
}
Edit:
Oh, and the example code outputs the following:
temp has 42 elements
factory._data has 0 elements