I am not able to use std::unique_ptr<>
while using CMake. This same code is compiling and running perfectly fine on Visual Studio 2012 but it is complaining with the following error while trying to compile on GCC 4.9.2:
test_uniqueptr/src/main.cpp:19:5: error: "unique_ptr" is not a member of "std"
std::unique_ptr<Foo> p1(new Foo); // p1 owns Foo
^
test_uniqueptr/src/main.cpp:19:24: error: expected primary-expression before ">" token
std::unique_ptr<Foo> p1(new Foo); // p1 owns Foo
^
test_uniqueptr/src/main.cpp:19:36: error: "p1" was not declared in this scope
std::unique_ptr<Foo> p1(new Foo); // p1 owns Foo
There is also another related error:
test_uniqueptr/src/main.cpp:34:9: error: "EXIT_SUCCESS" was not declared in this scope.
My source code is displayed below:
src/main.cpp:
#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 &)
{
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
return EXIT_SUCCESS;
}
CMakeLists.txt:
CMAKE_MINIMUM_REQUIRED( VERSION 2.8 )
SET( PROJECT_NAME Test_UniquePtr ) # change project name here
SET( SOURCE_DIRECTORY ${PROJECT_SOURCE_DIR}/src )
# Done for temporary testing
FILE( GLOB MainSources
"${SOURCE_DIRECTORY}/*.h"
"${SOURCE_DIRECTORY}/*.cpp"
)
INCLUDE_DIRECTORIES(
${CMAKE_CURRENT_BINARY_DIR}
${CMAKE_CURRENT_SOURCE_DIR}
)
ADD_EXECUTABLE(
${PROJECT_NAME}
${MainSources}
)
## Installation (optional)
SET_TARGET_PROPERTIES( ${PROJECT_NAME} PROPERTIES INSTALL_RPATH_USE_LINK_PATH TRUE )
INSTALL( TARGETS ${PROJECT_NAME} DESTINATION bin )
All the answers I have read indicate towards compiling the code using g++ main.cpp -std=c++11
but I want it to be done via CMake.