編輯:作出Foo
和Bar
少一點瑣事,並直接替換shared_ptr<>
更困難。應該使用unique_ptr來更輕鬆地實現「移動」語義?
應該可以作爲一個簡單的方法來實現移動語義?
對於一類像
class Foo
{
int* m_pInts;
bool usedNew;
// other members ...
public:
Foo(size_t num, bool useNew=true) : usedNew(useNew) {
if (usedNew)
m_pInts = new int[num];
else
m_pInts = static_cast<int*>(calloc(num, sizeof(int)));
}
~Foo() {
if (usedNew)
delete[] m_pInts;
else
free(m_pInts);
}
// no copy, but move
Foo(const Foo&) = delete;
Foo& operator=(const Foo&) = delete;
Foo(Foo&& other) {
*this = std::move(other);
}
Foo& operator=(Foo&& other) {
m_pInts = other.m_pInts;
other.m_pInts = nullptr;
usedNew = other.usedNew;
return *this;
}
};
實施舉動變得數據成員被添加比較繁瑣。但是,可移動數據可以放置在單獨的struct
中,其實例由管理。這使得=default
用於招:
class Bar
{
struct Data
{
int* m_pInts;
bool usedNew;
// other members ...
};
std::unique_ptr<Data> m_pData = std::make_unique<Data>();
public:
Bar(size_t num, bool useNew = true) {
m_pData->usedNew = useNew;
if (m_pData->usedNew)
m_pData->usedNew = new int[num];
else
m_pData->m_pInts = static_cast<int*>(calloc(num, sizeof(int)));
}
~Bar() {
if (m_pData->usedNew)
delete[] m_pData->m_pInts;
else
free(m_pData->m_pInts);
}
// no copy, but move
Bar(const Bar&) = delete;
Bar& operator=(const Bar&) = delete;
Bar(Bar&& other) = default;
Bar& operator=(Bar&& other) = default;
};
除了內存爲實例始終是在堆中,還有什麼其他問題,像這樣的實現存在嗎?
請'的std :: unique_ptr'應該使用,當且僅當資源的所有權是獨一無二的。在std :: unique_ptr上移動語義僅用於轉移所有權。 https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md –
@MathieuVanNevel是的,我打算通過'm_pInts'的操縱來轉移所有權。 –
什麼史前'calloc'? – SergeyA