将“noexcept”放在可能的 UB 上

问题描述 投票:0回答:1
struct A {
  int* a_ptr;
};

struct B {
  A* b_ptr;
};


struct C {  // iterator
  B* c_ptr;

  //...

  int& f() noexcept(?) {  // provides some access if 'C' is valid
    return c_ptr->b_ptr->a_ptr;
  }
};

想象一下:

C
是一些自定义迭代器,它始终有效,直到其容器被删除。否则,调用
C::f
将导致
UB
。我们相信用户永远不会尝试创建
C
、删除其容器,然后调用
C::f
(我们会警告他这是一个不好的做法)。

所以,问题是,从代码编写道德的角度来看,我是否可以将 noexcept(true)

 放在 
f
 上还是
上?我正在为任何决定寻找一些理由。

c++ function undefined-behavior noexcept
1个回答
0
投票
C++ 建立在未定义行为永远不会发生的假设之上

不存在任何程度的未定义行为

noexcept

 是关于 
your 代码抛出的异常,其中 throw my_exception

因此,如果一个函数从不抛出异常,但可以在不正确的使用情况下调用

UB

,那么适合放置 
noexcept(true)

    

© www.soinside.com 2019 - 2024. All rights reserved.