如何安全地将 new 创建的对象传递到构造函数中
How to safely pass objects created by new into constructor
我有几个类看起来像这样:
struct equation {};
struct number: equation {
number(int n): value(n) {}
private:
int value;
};
struct operation: equation {
operation(const equation* left, const equation* right)
: left(left), right(right) {}
private:
std::unique_ptr<equation> left, right;
};
它们的设计方式是operation
对传递给构造函数的指针取得所有权。
我的问题是我如何修改这个类以便能够以下一个方式安全地使用它:
operation op(new number(123), new number(456));
在我看来,如果第一个对象被创建而第二个对象没有创建(假设从构造函数中抛出异常number
那么这是一个内存泄漏 - 没有人会删除指向第一个数字的指针。
这种情况我该怎么办?我不想按顺序分配对象并在出现故障时删除它们 - 这太冗长了。
我不想按顺序分配对象并在出现故障时删除它们 - 它太冗长了。
是的。你只需要更彻底地应用智能指针习语;更准确地说,将参数类型更改为std::unique_ptr
,并使用std::make_unique
(自 C++14 起)(而不是显式使用new
)来避免此问题。例如
struct operation: equation {
operation(std::unique_ptr<equation> left, std::unique_ptr<equation> right)
: left(std::move(left)), right(std::move(right)) {}
private:
std::unique_ptr<equation> left, right;
};
然后
operation op(std::make_unique<number>(123), std::make_unique<number>(456));
请注意,std::make_unique
的使用在这里很重要,在std::make_unique
中创建的原始指针保证由返回的std::unique_ptr
管理;即使是第 2std::make_unique
也会失败。 由第一个std::make_unique
创建的std::unique_ptr
将确保它拥有的指针被销毁。对于首先调用第 2 个std::make_unique
的情况也是如此。
在C++14之前,你可以制作自己的std::make_unique
版本;一个基本的版本很容易编写。下面是一个可能的实现。
// note: this implementation does not disable this overload for array types
template<typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&&... args)
{
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
相关文章:
- 类中的 Arduino 对象构造函数设置垃圾值
- 编译错误:临时对象构造函数中缺少参数
- 双指针在使用 new 时不调用对象构造函数
- 以支持继承的方式将自身shared_ptr添加到对象构造函数中的向量中
- 在创建对象向量时,不为每个对象唯一调用默认对象构造函数
- GCC __attribute__((constructor)) 在对象构造函数之前调用
- 自定义对象构造函数在循环外部循环
- 从全局对象构造函数停止监视器计时器
- Arduino 上的 Sketch 停止在对象构造函数中执行
- 通过在引用线程对象来传递取消引用的“this”指针来在函数对象构造函数中创建线程是好是坏
- 为什么当对象构造函数投入新表达式时,为什么不调用DealLocation函数
- 临时结构对象构造函数奇数调用
- 未显式引用对象的全局对象构造函数在最终二进制文件 - LD 中被丢弃
- 为什么 Clang++ 不在另一个静态库中运行全局对象构造函数?
- 在未加载上下文的情况下在对象构造函数中使用OpenGL函数
- 为什么我们需要一个用户提供的const对象构造函数
- 对象构造函数的C++数组
- 将子结构值设置为对象构造函数中安全的纯虚拟函数返回的值
- C等价于新对象(构造函数)
- C++:直接在参数列表中使用数组文字的对象构造函数