【发布时间】:2019-08-02 02:11:47
【问题描述】:
标题说明了大部分内容,我该怎么做?我用谷歌搜索了一下,没有人告诉我它不能完成,但也没有人解释如何去做。
在此处获取这段代码:
#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);
^~~~~
【问题讨论】:
-
无关:if
std::make_uniqueis available to you 你应该养成使用它的习惯。它消除了构造函数和new无法保护您免受的一些错误情况。 -
问题是
std::unique_ptr本身也是一个struct,因此在这种类型的实例上使用.您试图访问std::unique_ptr的成员而不是它指向的结构。例如你可以调用方法get()- en.cppreference.com/w/cpp/memory/unique_ptr/getauto rawpointer = my_ptr.get();
标签: c++ c++11 struct unique-ptr