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

C++C++11G++Unique Ptr

C++ Problem Overview


I guess it's pretty self explanatory - I can't seem to use C++11 features, even though I think I have everything set up properly - which likely means that I don't.

Here's my code:

#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;
}

Here's my version of 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.

Here's how I'm compiling the code:

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

Note that I've tried both -std=c++11 and -std=c++0x to no avail.

I'm running Ubuntu 12.04 LTS from a flash drive on an Intel x64 machine.

C++ Solutions


Solution 1 - C++

You need to include header where unique_ptr and shared_ptr are defined

#include <memory>

As you already knew that you need to compile with c++11 flag

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

Solution 2 - C++

So here what I learned in 2020 - memory.h is at /usr/include AND in /usr/include/c++/4.8.5 and you need the second to be found before the first. In Eclipse set the order using Project->Properties->Path and Symbols->Includes->Add... path if needed and set first

Solution 3 - C++

You need to include #include that will solve the problem, at least on my ubunto linux machine

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionstellarossaView Question on Stackoverflow
Solution 1 - C++billzView Answer on Stackoverflow
Solution 2 - C++UziView Answer on Stackoverflow
Solution 3 - C++Oscar RangelView Answer on Stackoverflow