如何在struct上使用std :: unique_ptr

How to use std::unique_ptr on a struct?

本文关键字:std unique ptr struct      更新时间:2023-10-16

标题大部分都说,我该怎么做?我已经搜索了一些谷歌搜索,什么都没有告诉我它不能做,但是什么也没有解释如何做。

在此处进行此代码片段:

#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("%cn%in%fn",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("%cn%in%fn",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("%cn%in%fn",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("%cn%in%fn",my_ptr.first, my_ptr.second, my_ptr.third);
                                                               ^~~~~

您应该使用->而不是.std::unique_ptr是一个智能指针,其行为与原始指针相似。

my_ptr->first = 'A';
my_ptr->second = 2;
my_ptr->third = 3.00;
printf("%cn%in%fn",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("%cn%in%fn",(*my_ptr).first, (*my_ptr).second, (*my_ptr).third);

live

ps:您应该将"A"(这是C-Style字符串(更改为'A'(是char(。