错误:'unique_ptr'不是'std'的成员

ste*_*ssa 49 c++ g++ unique-ptr c++11

我想它是非常自我解释的 - 我似乎无法使用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;
}
Run Code Online (Sandbox Code Playgroud)

这是我的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.
Run Code Online (Sandbox Code Playgroud)

这是我编译代码的方式:

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
Run Code Online (Sandbox Code Playgroud)

请注意,我已经尝试了两个-std=c++11,-std=c++0x但无济于事.

我在Intel x64机器上的闪存驱动器上运行Ubuntu 12.04 LTS.

bil*_*llz 89

您需要包括头,其中unique_ptrshared_ptr定义

#include <memory>
Run Code Online (Sandbox Code Playgroud)

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

g++ main.cpp -o run -std=c++11
//                  ^
Run Code Online (Sandbox Code Playgroud)