在C++中创建非纯数据的unique_ptr

Creating unique_ptr of non plain data in C++

本文关键字:unique ptr 数据 C++ 创建      更新时间:2023-10-16

ptr 构造函数处理纯数据,但对对象失败:

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

为什么?

我的 g++ 版本是 (Ubuntu/Linaro 4.7.3-2ubuntu1~12.04) 4.7.3

实际上,这些初始化工作得很好 - 以下代码编译得很好,例如使用 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);
}

您提到它在 eclipse 中失败,因此您可以尝试通过以下方式禁用 eclipse 内部代码验证:

转到项目属性 -> C/C++ 常规 -> 代码分析 ->检查Use project settings,然后在Syntax and Semantic Errors取消选中所有错误行。

您可能需要从输出中删除以前的错误,只需选择它们并删除即可。

实际上有一行模式为"函数{0}无法解析",通常 g++ 不会给你这样的错误(我至少从未见过这样的错误)