這是一流的設計標準的C++ 0x防止副本和分配,以保護客戶端代碼免受意外data
雙缺失呢?把不可複製的對象爲STD-容器
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;
}
};
您會注意到,我在這裏和移動指派方法來定義新的舉措。我是否正確實施它們?
有什麼辦法,我可以 - 與移動和移動指派定義 - 把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
想法只是一個猜測,在這裏。
編輯:爲了讀者的方便,我將答案寫入了示例代碼。
const RValue引用? – 2011-04-16 15:29:38