I have the following very simple class:
class Foo
{
public:
Foo() {}
Foo(const Foo&) = delete;
Foo(Foo&&) {}
void operator=(const Foo&) = delete;
void operator=(Foo&&) {}
void dump() const {}
};
The class is move constructible and assignable but isn't copy constructible and assignable.
I'd like to initialize a vector of Foo elements using vector's initializer list.
std::vector<Foo> vf = { Foo() };
The compiler complains because code has to use the deleted copy constructor. Could anybody explain, why the move construct is not used in this case, and why copy of the object is needed?
The following also requires the copy constructor and does not work either:
std::vector<Foo> vf = { std::move(Foo()) };
On the other hand, this works fine (the move constructor is called):
std::vector<Foo> vf;
vf.push_back(Foo());
Thanks for the explanation... :)
Update:
A suggested this post explains my question.
Furthermore let's consider the following code (together with class Foo
above):
class Bar {
public:
Bar(std::initializer_list<Foo> _l) {
std::cout << "Bar::Bar()" << std::endl;
for (auto& e : _l)
e.dump();
}
};
int main() {
Bar b { Foo() };
return 0;
}
This produces the following output (compiled with C++11):
Foo::Foo()
Bar::Bar()
Foo::dump()
Foo::~Foo()
It can be seen, that the initializer list is not actually filled with the 'copy of the objects' stated between the braces. This might be not true from C++14.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…