我正在学习如何使用条件noexcept并遇到这个问题。假设我有一个类:templateclassWrapper{public:Wrapper(T&&value)noexcept(/*???*/):value_(std::move(value)){}private:Tvalue_;};对于/*???*/部分,我想我们可以使用noexcept(T(std::move(value)))或std::is_nothrow_move_constructible::value,直到我偶然发现this.所以如果我使用noexcept(noexcept(T(std::move(value)))),严格来
我已经编写了以下代码来测试跨函数调用的noexcept传播,它似乎并没有像我想象的那样工作。在GCC4.7.2中,可以有效地测试函数是否为noexcept仅直接或作为模板特化参数传递时;但不是当作为参数传递给模板函数时,或作为指向普通函数的函数指针时——即使该函数将其形式参数声明为noexcept。这是代码:#include#definetest(f)\std::coutstaticinlinevoidtest0(){test(f);}templatestaticinlinevoidtest1(Ff){test(f);}staticinlinevoidtest2(void(*f)())
尽管我的代码编译得很好,但这一直困扰着我,我无法在stackoverflow上找到答案。以下通用构造函数是将shared_ptr传递给构造函数中的类实例的一种方法。MyClass{MyClass(conststd::shared_ptr&pt);std::shared_ptrpt_;//EDITED:Removed&typo};MyClass::MyClass(conststd::shared_ptr&pt):pt_(pt){}这编译得很好。我的问题如下:在我的理解中,像这样声明一个参数const:voidmyfunc(constT&t)promise不改变t。但是,通过将shared
考虑以下C++代码:typedefstd::string&mutable_string_ref;conststd::stringstr="abc";mutable_string_refref(str);这显然会导致编译器错误,因为您无法创建对常量字符串的可变引用。对于GCC4.7.2,产生的错误是:error:invalidinitializationofreferenceoftype‘mutable_string_ref{akastd::basic_string&}’fromexpressionoftype‘conststring{akaconststd::basic_string}
这是value_or()的定义来自C++17标准:templateconstexprTvalue_or(U&&v)const&;Effects:Equivalentto:returnbool(*this)?**this:static_cast(std::forward(v));Remarks:Ifis_copy_constructible_v&&is_convertible_visfalse,theprogramisill-formed.(右值重载类似)value_or的效果被描述为等同于returnbool(*this)?**this:static_cast(std::forward
当我定义一个constexpr函数时,我是否也应该将它声明为noexcept?我想在参数和用法满足编译时评估要求的情况下,潜在异常的含义是没有实际意义的。但对于在运行时评估函数的情况,它会照常适用。作为一个实际问题,如果函数确实简单,可能使用内置算术或转换,这样我希望编译器始终可以内联函数并对其进行优化,如果我离开noexcept对生成代码的效率有影响吗? 最佳答案 不,你不应该。“不能失败”和“可以在编译时求值”是正交问题。例如,你想写一个整数幂函数,但你想把幂作为有符号的(因为你认为无符号数应该只用于非常特殊的情况)。现在你说你
假设我有以下代码:classA{public:voidSetInteger(constintval)noexcept{integerMember=val;}voidSetString(conststd::string&val){stringMember=val;}intGetInteger()constnoexcept{returnintegerMember;}std::stringGetString()const{returnstringMember;}private:intintegerMember;std::stringstringMember;}对我来说,对整数类型和指针使用n
对于下面的代码structX{intx;X()noexcepttry:x(0){}catch(...){}};VisualStudio14CTP发出警告warningC4297:'X::X':functionassumednottothrowanexceptionbutdoesnote:__declspec(nothrow),throw(),noexcept(true),ornoexceptwasspecifiedonthefunction这是对noexcept的误用吗?还是Microsoft编译器中的错误? 最佳答案 Orisit
假设您有一个通常永远不会失败的函数,例如:std::stringconvert_integer_to_string(intx);原则上,这将是noexcept的候选者。但是,实现很可能涉及动态内存管理,因此它总是会抛出std::bad_alloc。使用new运算符分配内存时。是否建议将函数注释为noexcept?从实际的角度来看,以合理的方式处理内存不足的情况是极其困难的。大多数程序只是假设有足够的可用内存。调用std::terminate,就像如果noexcept函数抛出std::bad_alloc时会发生的那样,在这种情况下似乎是合理的。对我来说,noexcept是某种形式的文档。
考虑:classtest{private:intn;intimpl()constnoexcept{returnn;}public:test()=delete;test(intn)noexcept:n(n){}intget()constnoexcept(noexcept(impl())){returnimpl();}};海湾合作委员会拒绝:test.cpp:27:43:error:cannotcallmemberfunction'inttest::impl()const'withoutobjectintget()constnoexcept(noexcept(impl())){类似地:te