Skip to content

Instantly share code, notes, and snippets.

@fortheday
Last active January 31, 2018 08:37
Show Gist options
  • Save fortheday/c4aa2f5c56611cd1b55ef113066e9f1f to your computer and use it in GitHub Desktop.
Save fortheday/c4aa2f5c56611cd1b55ef113066e9f1f to your computer and use it in GitHub Desktop.
struct SData
{
int m_Size;
char *m_Buf;
SData()
: m_Size(0), m_Buf(nullptr)
{
puts("ctor");
}
void Alloc(int size)
{
m_Size = size;
m_Buf = new char[size];
puts("alloc");
}
SData(int size)
: m_Size(size), m_Buf(new char[size])
{
puts("ctor(size)");
}
SData(const SData &rRight)
: m_Size(rRight.m_Size), m_Buf(new char[rRight.m_Size])
{
puts("ctor-copy");
memcpy(m_Buf, rRight.m_Buf, m_Size);
}
SData(SData &&rrRightBeMoved)
: m_Size(rrRightBeMoved.m_Size), m_Buf(rrRightBeMoved.m_Buf)
{
puts("ctor-move");
rrRightBeMoved.m_Buf = nullptr;
}
~SData()
{
puts("dtor");
if (m_Buf != nullptr) {
puts("delete buf");
delete[] m_Buf;
}
}
};
using namespace std;
vector<SData> vec;
vec.reserve(10);
// 기존 최적화 스타일, 여전히 가장 빠른코드
{
vec.resize(vec.size() + 1); // ctor
SData &rNewData = vec.back();
rNewData.Alloc(64); // alloc
// rNewData 처리
}
// 지역변수를 컨테이너에 그냥 넣으면 (lvalue)
{
SData newData(64); // ctor(size)
// newData 처리
vec.push_back(newData); // ctor-copy
// dtor(newData), delete buf
}
// C++11 이후 생산효율적인 타협 가능한 코드 (lvalue as rvalue)
{
SData newData(64); // ctor(size)
// newData 처리
vec.push_back(move(newData)); // ctor-move (shallow copy)
// dtor(newData), no delete
}
// 좀더 줄이면 (rvalue로 취급, 성능은 직전과 같음)
{
vec.push_back( // ctor(size), ctor-move, dtor(no delete)
SData {
64
// ...
});
}
_getch();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment