错误:“unique_ptr”不是“std”的成员

error: ‘unique_ptr’ is not a member of ‘std’

本文关键字:不是 std 成员 ptr unique 错误      更新时间:2023-10-16

我想这是不言自明的 - 我似乎无法使用 C++11 功能,即使我认为我已经正确设置了所有内容 - 这可能意味着我没有。

这是我的代码:

#include <cstdlib>
#include <iostream>
class Object {
    private:
        int value;
    public:
        Object(int val) {
            value = val;
        }
        int get_val() {
            return value;
        }
        void set_val(int val) {
            value = val;
        }
};
int main() {
    Object *obj = new Object(3);
    std::unique_ptr<Object> smart_obj(new Object(5));
    std::cout << obj->get_val() << std::endl;
    return 0;
}

这是我的 g++ 版本:

ubuntu@ubuntu:~/Desktop$ g++ --version
g++ (Ubuntu/Linaro 4.7.3-2ubuntu1~12.04) 4.7.3
Copyright (C) 2012 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

以下是我编译代码的方式:

ubuntu@ubuntu:~/Desktop$ g++ main.cpp -o run --std=c++11
main.cpp: In function ‘int main()’:
main.cpp:25:2: error: ‘unique_ptr’ is not a member of ‘std’
main.cpp:25:24: error: expected primary-expression before ‘>’ token
main.cpp:25:49: error: ‘smart_obj’ was not declared in this scope

请注意,我已经尝试了-std=c++11-std=c++0x都无济于事。

我正在从英特尔 x64 机器上的闪存驱动器运行 Ubuntu 12.04 LTS。

您需要在定义unique_ptrshared_ptr的地方包含标头

#include <memory>

正如您已经知道的那样,您需要使用c++11标志进行编译

g++ main.cpp -o run -std=c++11
//                  ^

所以这是我在 2020 年学到的 - memory.h 位于/usr/include/c++/4.8.5 中的/usr/include AND 中,您需要在第一个之前找到第二个。在 Eclipse 中,使用 Project->Properties->Path 和 Symbols->Include->Add...路径(如果需要(并首先设置

你需要

包含可以解决问题 #include,至少在我的ubunto Linux机器上