小编Ann*_*nyo的帖子

约束函数会允许模板参数取决于函数参数吗?

在C ++ 17中,此代码是非法的:

constexpr int foo(int i) {
    return std::integral_constant<int, i>::value;
}
Run Code Online (Sandbox Code Playgroud)

这是因为即使foo可以在编译时进行评估,编译器仍然需要产生指令以在运行时执行它,从而使模板实例化成为不可能。

在C ++ 20中,我们将具有consteval需要在编译时评估的函数,因此应删除运行时约束。这是否意味着该代码将是合法的?

consteval int foo(int i) {
    return std::integral_constant<int, i>::value;
}
Run Code Online (Sandbox Code Playgroud)

c++ language-lawyer class-template constexpr c++20

55
推荐指数
3
解决办法
1521
查看次数

为什么在此constexpr函数中允许std :: swap?

我编写了一个计算两个数字的gcd的函数,该函数std::swap在第二个参数大于第一个参数的情况下使用。

一段时间后,我意识到,std::swap不是 constexpr,但我仍然函数编译并运行成功。
我尝试使用MinGW-w64 8.1.0和Visual C ++ 2017,并且对两者均有效。

我的第一个想法是,因为constexpr允许在运行时执行功能,所以我尝试了std::integral_constant<int,gcd(32,12)>,并且奏效了。

但是,我不能使用自己的任何非constexpr函数(这是我期望的)。

这是我的测试代码:

#include <utility>

inline void foo() noexcept {
}

template<typename T>
constexpr T gcd(T a, T b) {
    // foo();            // only works with non-constexpr j
    if(a<b) {
        std::swap(a, b); // works for both constexpr i and non-constexpr j
    }
    if(b==0) {
        return a;
    } else {
        return gcd(b, a%b);
    }
}

int main()
{
    constexpr int i = std::integral_constant<int, …
Run Code Online (Sandbox Code Playgroud)

c++ c++17

6
推荐指数
1
解决办法
267
查看次数

std::shared_ptr 在空指针上调用非默认删除器

看这个例子:

#include <iostream>
#include <memory>

class Foo {
public:
    Foo()  { std::cout << "Foo()\n";  }
    ~Foo() { std::cout << "~Foo()\n"; }
};

int main(){
    auto deleter = [](Foo* p) {
        if(!p) { std::cout << "Calling deleter on nullptr\n"; }
        delete p;
    };

    std::shared_ptr<Foo> foo;
    std::cout << "\nWith non-null Foo:\n";
    foo = std::shared_ptr<Foo>(new Foo, deleter);
    std::cout << "foo is " << (foo ? "not ":"") << "null\n";
    std::cout << "use count=" << foo.use_count() << '\n';
    foo.reset();

    std::cout << "\nWith nullptr and …
Run Code Online (Sandbox Code Playgroud)

c++ smart-pointers reference-counting shared-ptr

6
推荐指数
1
解决办法
1146
查看次数