Creating unique_ptr of non plain data in C++
-
21-12-2019 - |
题
The ptr constructors works with plain data but fails with objects:
#include <string>
#include <memory>
struct MyClass{};
int main() {
std::unique_ptr<int> ptr(new int(5));
std::unique_ptr<std::string> ptr1(new std::string("string")); //function 'ptr1' could not be resolved.
std::unique_ptr<MyClass> ptr2(new MyClass); //unction 'ptr2' could not be resolved.
return 0;
}
why?
My g++ version is (Ubuntu/Linaro 4.7.3-2ubuntu1~12.04) 4.7.3
解决方案
You mentioned it fails in eclipse, so you might try disabling eclipse internal code validation, by:
going to project properties -> C/C++ General -> Code Analysis -> check Use project settings
and then in Syntax and Semantic Errors
uncheck all Error lines.
You might need to delete previous errors from output, by simply selecting them and deleting.
Actually there is one line with pattern 'Function ''{0}'' could not be resolved', normally g++ would not give you such error (I at least never seen such)
其他提示
Actually, these initializations work just fine - the following code compiles fine e.g. with g++ 4.8.2:
#include <memory>
#include <string>
struct MyClass { };
int main()
{
std::unique_ptr<int> ptr(new int(5));
std::unique_ptr<std::string> ptr1(new std::string("string"));
std::unique_ptr<MyClass> ptr2(new MyClass);
}