UPD: The linked duplicate question do indeed resolve the issue. Thank you, everyone, for your suggestions.
Suppose I have the following class:
class NonCopyableInt {
public:
NonCopyableInt(const int &source) : data{source} {
}
NonCopyableInt(const NonCopyableInt &val) = delete;
void operator=(const NonCopyableInt &other) = delete;
NonCopyableInt(NonCopyableInt &&val) {
data = val.data;
}
int data;
};
Now, I'm using it this way:
template<typename T>
ostream &operator<<(ostream &os, const vector<T> &vec) {
for (const auto &v : vec) {
os << v << " ";
}
return os;
}
ostream &operator<<(ostream &os, const NonCopyableInt &v) {
os << v.data << " ";
return os;
}
int main(){
{
cout << "partial move" << endl;
vector<NonCopyableInt> v;
v.push_back(NonCopyableInt(1));
v.push_back(NonCopyableInt(2));
v.push_back(NonCopyableInt(3));
v.push_back({3});
vector<NonCopyableInt> vref;
cout << v << endl;
cout << vref << endl;
vref.push_back(move(v[0]));
v.clear();
cout << v << endl;
cout << vref << endl;
}
return 0;
}
This works perfectly fine and as expected. I am able to move objects between vectors without copying them. However, here is my question:
Why can I do this:
v.push_back({3});
But can't do this(causes the following compilation error: error: call to deleted constructor of 'NonCopyableInt'
):
vector<NonCopyableInt> v{{1},{2}}
? My guess is that when I call vector constructor, it can't accept element by rvalue or what?
Thank you.