如果对象的构造函数不是except,可以放置new (expression)抛出
Can placement new (expression) throw if the constructor of the object is noexcept?
template <class T>
struct Obj {
// Plain Old Data for T
using InternalPod = typename std::aligned_storage<sizeof(T), std::alignment_of<T>::value>::type;
InternalPod value_pod_;
template<class... Args>
Obj(Args&&... args) { // my constructor
// placement new: construct the value in the statically allocated space
new (&value_pod_) T(std::forward<Args>(args)...); // <- can this whole expression throw if the constructor of T doesn’t throw?
}
}
Normal new
可以在分配失败或构造失败时抛出(如果有其他情况请纠正我),但是由于位置new不分配任何空间,如果T
的构造函数不抛出,new表达式可以抛出吗?
。以下noexcept
规格是否正确安全?
Obj(Args&&... args) noexcept(noexcept(T(std::forward<Args>(args)...))) {
new (&value_pod_) T(std::forward<Args>(args)...);
}
根据18.6 [support]将<new>
中的位置new
声明为noexcept
。动态]第1段:
…
void* operator new (std::size_t size, void* ptr) noexcept;
…
使用new
表达式时,系统只做两件事:
- 调用相应版本的
operator new()
来获取内存。如果内存分配失败,它应该为没有noexcept
资格的operator new()
抛出std::bad_alloc
,否则返回nullptr
。 - 如果返回非
nullptr
,则该表达式调用new
表达式中该类型的构造函数。如果此构造失败并出现异常,则调用与被调用operator new()
匹配的operator delete()
,并使用该operator new()
的结果。
由于内存分配不可能失败,获得异常的唯一选项是从该类型的构造函数
相关文章:
- "throw expression code" 1e7 >返回 d 是什么?投掷标准::overflow_error( "too big" ) : d;意味 着?
- 如果"new int"返回"int*",那么为什么"new int[n]"不返回"int**"?
- 有没有一种方法可以使用placement new将堆叠对象分配给分配的内存
- 重载运算符new[]的行为取决于析构函数
- 过载'operator new'如何导致无限循环?
- 创建具有 new in 函数和"this is nullptr"异常的对象
- Codelite C++ new project
- 为什么static_assert错误:即使我传递常量"expression must have a constant value"?
- 在类c++中使用new声明数组
- g++用户定义的动态链接库上的全局new和delete运算符
- C++ "error: invalid use of void expression"
- 如果整个应用程序是虚拟映射的,为什么 new 会进行系统调用?
- 在将 new 与指针一起使用时,创建数组的指定长度
- "Warning: Comma within array index expression"但逗号分隔函数参数
- 对象声明中的模板"error: expected expression"
- 为什么我的功能在使用 goto 时会给我带来"expected primary-expression before '}' token"?
- 体系结构x86_64的未定义符号:std:terminate(),typeinfo,运算符delete[],运算符new
- 为什么我的全局 new() 覆盖被绕过了?
- 让编译器告诉哪些方法不具体,而不是错误'invalid new-expression of abstract class type'
- 如果对象的构造函数不是except,可以放置new (expression)抛出