此类是否设计了标准 C++0x 方法来防止复制和分配,以保护客户端代码免受意外双重删除data
?
struct DataHolder {
int *data; // dangerous resource
DataHolder(const char* fn); // load from file or so
DataHolder(const char* fn, size_t len); // *from answers: added*
~DataHolder() { delete[] data; }
// prevent copy, to prevent double-deletion
DataHolder(const DataHolder&) = delete;
DataHolder& operator=(const DataHolder&) = delete;
// enable stealing
DataHolder(DataHolder &&other) {
data=other.data; other.data=nullptr;
}
DataHolder& operator=(DataHolder &&other) {
if(&other!=this) { data = other.data; other.data=nullptr};
return *this;
}
};
你注意到了,我在这里定义了新的move和move-assign方法。我是否正确实施了它们?
有什么方法可以 - 使用move和move-assign定义 - 放入DataHolder
标准容器中?像一个vector
?我该怎么做?
我想知道,我想到了一些选择:
// init-list. do they copy? or do they move?
// *from answers: compile-error, init-list is const, can nor move from there*
vector<DataHolder> abc { DataHolder("a"), DataHolder("b"), DataHolder("c") };
// pushing temp-objects.
vector<DataHolder> xyz;
xyz.push_back( DataHolder("x") );
// *from answers: emplace uses perfect argument forwarding*
xyz.emplace_back( "z", 1 );
// pushing a regular object, probably copies, right?
DataHolder y("y");
xyz.push_back( y ); // *from anwers: this copies, thus compile error.*
// pushing a regular object, explicit stealing?
xyz.push_back( move(y) );
// or is this what emplace is for?
xyz.emplace_back( y ); // *from answers: works, but nonsense here*
这个emplace_back
想法只是一个猜测,在这里。
编辑:为了方便读者,我将答案放入示例代码中。