如果在其构造函数的内存分配过程中出现问题,我想确保它正确展开。
那么你必须让你的代码符合“一个类控制一种资源或做一项工作”的思想
#include <memory>
// foo has one job - to manage fooness.
// It no longer manages memory resources
class foo
{
public:
foo()
: var1(new int(1))
, var2(new int(2))
{
}
std::unique_ptr<int> var1; // unique_ptr only manages a resource
std::unique_ptr<int> var2; // unique_ptr only manages a resource
};
其他正确的初始化形式:
#include <memory>
// foo has one job - to manage fooness.
// It no longer manages memory resources
class foo
{
public:
foo()
: var1(std::make_unique<int>(1))
, var2(std::make_unique<int>(2))
{
}
std::unique_ptr<int> var1; // unique_ptr only manages a resource
std::unique_ptr<int> var2; // unique_ptr only manages a resource
};
默认值:
#include <memory>
// foo has one job - to manage fooness.
// It no longer manages memory resources
class foo
{
public:
// default constructor now implicit
std::unique_ptr<int> var1 = std::make_unique<int>(1); // unique_ptr only manages a resource
std::unique_ptr<int> var2 = std::make_unique<int>(2); // unique_ptr only manages a resource
};
正确,但习惯上令人不快 - 冗余初始化:
#include <memory>
// foo has one job - to manage fooness.
// It no longer manages memory resources
class foo
{
public:
foo()
: var1(nullptr)
, var2(nullptr)
{
var1 = std::make_unique<int>(1);
var2 = std::make_unique<int>(2);
}
std::unique_ptr<int> var1; // unique_ptr only manages a resource
std::unique_ptr<int> var2; // unique_ptr only manages a resource
};
这是一种无需组合即可完成的方法。请注意所有额外的复杂性,但没有任何收获:
#include <memory>
// foo now has two jobs - to manage fooness, and to manage resources.
// This adds un-necessary complication, bugs and maintenance overhead
class foo
{
public:
foo()
: var1(nullptr)
, var2(nullptr)
{
var1 = new int(1);
var2 = new int(2);
}
foo(const foo& other)
: var1(nullptr)
, var2(nullptr)
{
if (other.var1) {
var1 = new int(*(other.var1));
}
if (other.var2) {
var2 = new int(*(other.var2));
}
}
foo(foo&& other) noexcept
: var1(other.var1)
, var2(other.var2)
{
other.var1 = nullptr;
other.var2 = nullptr;
}
foo& operator=(const foo& other)
{
foo tmp(other);
std::swap(var1, tmp.var1);
std::swap(var2, tmp.var2);
return *this;
}
foo& operator=(foo&& other) noexcept
{
foo tmp(std::move(other));
std::swap(var1, tmp.var1);
std::swap(var2, tmp.var2);
return *this;
}
~foo() noexcept
{
delete var1;
delete var2;
}
int* var1; // doesn't manage anything
int* var2; // doesn't manage anything
};