c++ - 如何使用 Orwell Dev-C++ 编译 C++11 代码?

标签 c++ c++11 unique-ptr dev-c++

尝试编译以下代码:

#include <iostream>
#include <memory>

struct Foo {
    Foo() { std::cout << "Foo::Foo\n"; }
    ~Foo() { std::cout << "Foo::~Foo\n"; }
    void bar() { std::cout << "Foo::bar\n"; }
};

void f(const Foo &foo)
{
    std::cout << "f(const Foo&)\n";
}

int main()
{
    std::unique_ptr<Foo> p1(new Foo);  // p1 owns Foo
    if (p1) p1->bar();

    {
        std::unique_ptr<Foo> p2(std::move(p1));  // now p2 owns Foo
        f(*p2);

        p1 = std::move(p2);  // ownership returns to p1
        std::cout << "destroying p2...\n";
    }

    if (p1) p1->bar();

    // Foo instance is destroyed when p1 goes out of scope
}

使用 Orwell Dev-c++ 5.3.0.3 会产生以下错误:

'unique_ptr' is not a member of 'std'.

我该如何处理?

最佳答案

请确保在编译时提供正确的 -std 标志。 Orwell Dev-C++ 使用的默认设置(不传递任何 -std 选项)不会启用一些 Shiny 的新 C++11 函数,例如 unique_ptr。修复非常简单:

  • 对于非项目编译,转到:工具 >> 编译器选项 >>(选择您的编译器)>> 设置 >> 代码生成 >>(将“语言标准”设置为 C++11 选项)
  • 对于项目编译,转到:项目 >> 编译器 >> 代码生成 >>(将“语言标准”设置为 C++11 选项)

这里有一些关于 -std 标志的更多信息: http://gcc.gnu.org/onlinedocs/gcc/C-Dialect-Options.html#C-Dialect-Options

如您所见,GCC 默认使用 C++03 的 GNU 方言(似乎不支持 unique_ptr)。

关于c++ - 如何使用 Orwell Dev-C++ 编译 C++11 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13613295/

相关文章:

c++ - windows中宽字符和多字节字符串之间如何相互转换?

c++ - 如何在编译时包含数据文件?

c++ - 命名空间名称在范围内必须是唯一的。为什么?

c++ - 理解 C++ 中的 std::move 和使用 std::unique_ptr 的所有权转移

c++ - 如何转发声明自定义unique_ptr

c++ - 什么时候使用内联函数,什么时候不使用它?

c++ - 将属性表制作为 MDI 子项

c++ - operator << 用于模板类的内部类

python - 使用 boost::python 公开具有 std::function 作为参数的 C++ 成员函数

c++ - 唯一指针 : pointer being freed was not allocated when emplaced in list