MemoryBlock
クラスのマイC++ 11バージョン。正しいC++コンパイラで11
#include <algorithm>
#include <vector>
// #include <stdio.h>
class MemoryBlock
{
public:
explicit MemoryBlock(size_t length)
: length_(length),
data_(new int[length])
{
// printf("allocating %zd\n", length);
}
~MemoryBlock() noexcept
{
delete[] data_;
}
// copy constructor
MemoryBlock(const MemoryBlock& rhs)
: MemoryBlock(rhs.length_) // delegating to another ctor
{
std::copy(rhs.data_, rhs.data_ + length_, data_);
}
// move constructor
MemoryBlock(MemoryBlock&& rhs) noexcept
: length_(rhs.length_),
data_(rhs.data_)
{
rhs.length_ = 0;
rhs.data_ = nullptr;
}
// unifying assignment operator.
// move assignment is not needed.
MemoryBlock& operator=(MemoryBlock rhs) // yes, pass-by-value
{
swap(rhs);
return *this;
}
size_t Length() const
{
return length_;
}
void swap(MemoryBlock& rhs)
{
std::swap(length_, rhs.length_);
std::swap(data_, rhs.data_);
}
private:
size_t length_; // note, the prefix underscore is reserved.
int* data_;
};
int main()
{
std::vector<MemoryBlock> v;
// v.reserve(10);
v.push_back(MemoryBlock(25));
v.push_back(MemoryBlock(75));
v.insert(v.begin() + 1, MemoryBlock(50));
}
、MemoryBlock::MemoryBlock(size_t)
は唯一のテストプログラムで3回呼び出さなければなりません。
ここには良いアドバイスがありますが、この回答は、重複コードのコストが2回目の書き込みに費やされる以上のものであることを考慮していないと思います。可読性、保守性、堅牢性よりもはるかに重要なコストがかかります。具体的には、コードが重複している場合、非常に一般的なタイプのバグ、すなわちコードの1つのインスタンスで何かが修正または変更された場合、他のインスタンスではなくバグが発生します。私が人生で気にするよりも多くの時間で噛まれたことで、証明された非常に強力な理由がない限り、私はコードを複製しません。 –
パフォーマンスは理由の1つですが、唯一または最も重要なものではありません。私のクラスはリソースの一意の所有権を持っているため、ほとんどの場合、移動コンストラクタと移動代入演算子を記述します。しばしばパフォーマンスは問題ではないので、重複を避けることは理にかなっています。 – opetroch
@ user779446:ご協力いただきありがとうございます。 http://howardhinnant.github.io/coding_guidelines.html –