c++ - 如何在结构上使用 std::unique_ptr?

标签 c++ c++11 struct unique-ptr

标题说明了大部分内容,我该怎么做?我在 Google 上搜索了一下,没有人告诉我这是不可能的,但也没有人解释如何去做。

将这段代码放在这里:

#include <cstdio>
#include <memory>

int main(void)
{
    struct a_struct
    {
        char first;
        int second;
        float third;
    };

    std::unique_ptr<a_struct> my_ptr(new a_struct);

    my_ptr.first = "A";
    my_ptr.second = 2;
    my_ptr.third = 3.00;

    printf("%c\n%i\n%f\n",my_ptr.first, my_ptr.second, my_ptr.third);

    return(0);
}

能够回答这个问题的人已经知道,这是行不通的,它甚至无法编译。

我的问题是如何让这样的东西发挥作用?

编译错误(使用g++-7)看起来像

baduniqueptr6.cpp: In function ‘int main()’:
baduniqueptr6.cpp:15:12: error: ‘class std::unique_ptr<main()::a_struct>’ has no member named ‘first’
     my_ptr.first = "A";
            ^~~~~
baduniqueptr6.cpp:16:12: error: ‘class std::unique_ptr<main()::a_struct>’ has no member named ‘second’
     my_ptr.second = 2;
            ^~~~~~
baduniqueptr6.cpp:17:12: error: ‘class std::unique_ptr<main()::a_struct>’ has no member named ‘third’
     my_ptr.third = 3.00;
            ^~~~~
baduniqueptr6.cpp:19:34: error: ‘class std::unique_ptr<main()::a_struct>’ has no member named ‘first’
     printf("%c\n%i\n%f\n",my_ptr.first, my_ptr.second, my_ptr.third);
                                  ^~~~~
baduniqueptr6.cpp:19:48: error: ‘class std::unique_ptr<main()::a_struct>’ has no member named ‘second’
     printf("%c\n%i\n%f\n",my_ptr.first, my_ptr.second, my_ptr.third);
                                                ^~~~~~
baduniqueptr6.cpp:19:63: error: ‘class std::unique_ptr<main()::a_struct>’ has no member named ‘third’
     printf("%c\n%i\n%f\n",my_ptr.first, my_ptr.second, my_ptr.third);
                                                               ^~~~~

最佳答案

你应该使用 ->而不是 .std::unique_ptr 是一个 smart pointer它的行为类似于原始指针。

my_ptr->first = 'A';
my_ptr->second = 2;
my_ptr->third = 3.00;

printf("%c\n%i\n%f\n",my_ptr->first, my_ptr->second, my_ptr->third);

LIVE

或者您可以使用 operator*取消对指针的引用,然后您可以使用 operator.,这也与原始指针相同。

(*my_ptr).first = 'A';
(*my_ptr).second = 2;
(*my_ptr).third = 3.00;

printf("%c\n%i\n%f\n",(*my_ptr).first, (*my_ptr).second, (*my_ptr).third);

LIVE

PS:您应该将 "A"(这是一个 C 风格的字符串)更改为 'A'(这是一个 char ).

关于c++ - 如何在结构上使用 std::unique_ptr?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57319087/

相关文章:

c++ - auto 是如何推断类型的?

c++ - 预订 "Programming Role Playing Games with DirectX 2nd edition"和更新的 DirectX api

c++ - 如何在 visual studio 中使用处理器寄存器?

c++ - 在类模板中定义一种本地类

c++ - 使用 C++11 无限制 union 时的 VS 2013 异常

c++ - 此输出有效还是编译器错误?

c++ - 编译时已知数组大小 : passed compilation using g++ but not for icpc

c++ - 从文件读入结构并添加到 vector

c# - 对您来说它看起来像 C# 错误吗?

c++ - n 维中最近对中的错误