【发布时间】:2011-08-06 22:43:47
【问题描述】:
这个类是否设计了标准的 C++0x 方法来防止 copy 和 assign,以保护客户端代码免受 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 的想法在这里只是一个猜测。
编辑:为了方便读者,我将答案放入示例代码中。
【问题讨论】:
-
const RValue 引用?
标签: c++ stl c++11 rvalue-reference noncopyable