error C2429: 语言功能 ;if/switch 中的 init-statement;需要编译器标志;/std:c++17

#include <iostream>
#include <iomanip>
#include <memory>

using namespace std;

struct Foo {
    int value;

    Foo(int i) : value{i} {}
    ~Foo() { cout << "DTOR Foo " << value << '\n'; }
};

void weak_ptr_info(const weak_ptr<Foo> &p)
{
    cout << "---------" << boolalpha
         << "\nexpired:   " << p.expired()
         << "\nuse_count: " << p.use_count()
         << "\ncontent:   ";

    //c++17 新特性
    if (const auto sp (p.lock()); sp) {
        cout << sp->value << '\n';
    } else {
        cout << "<null>\n";
    }
}


int main()
{
    weak_ptr<Foo> weak_foo;

    weak_ptr_info(weak_foo);

    {
        auto shared_foo (make_shared<Foo>(1337));
        weak_foo = shared_foo;

        weak_ptr_info(weak_foo);
    }

    weak_ptr_info(weak_foo);
}

用vs2017的时候会出现如下报错,解决办法如下:

工程属性--c/c++ 所有选项--c++语言标准  iso c++17标准(/std:c++17)

1>f:\code_pro\weakptr\weakptr\weakptr.cpp(27): error C2429: 语言功能 "if/switch 中的 init-statement" 需要编译器标志 "/std:c++17"

猜你喜欢

转载自blog.csdn.net/jangdong/article/details/81105820