使用CMake时我无法使用std::unique_ptr<>
。这个相同的代码在Visual Studio 2012上编译和运行完全正常,但在尝试在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
还有另一个相关的错误:
test_uniqueptr/src/main.cpp:34:9: error: "EXIT_SUCCESS" was not declared in this scope.
我的源代码如下所示:
的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 )
我读过的所有答案都表明要使用g++ main.cpp -std=c++11
编译代码,但我希望通过CMake完成。