如何在struct上使用std :: unique_ptr
How to use std::unique_ptr on a struct?
标题大部分都说,我该怎么做?我已经搜索了一些谷歌搜索,什么都没有告诉我它不能做,但是什么也没有解释如何做。
在此处进行此代码片段:
#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
(。
相关文章:
- 使用std::multimap迭代器创建std::list
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- 为什么 std::unique 不调用 std::sort?
- 我对 std::unique(算法)C++有问题
- std::shared_ptr::unique(),复制和线程安全
- 如何在C++03中用自定义谓词调用std::unique
- C++ std::unique并没有显示我对它的期望
- C++14 unique_ptr并使用已删除的函数'std::unique-ptr' unique_ptr错误
- 为什么 [std::unique] 不能应用于 [std::multiset]?
- 使用 std::unique 和 vector.erase 删除除最后一次出现的重复元素之外的所有元素
- 是否可以在 std::unique<T[ ]> 上应用 std::sort?
- std::unique 是否有大小限制
- 从 std::unique 返回的迭代器的用法
- 使 std::unique<T> 与 std::unique<const T, CustomDeleterType 兼容>
- Std::list.unique()应该使迭代器无效
- 无法使用初始化器列表构造 vector<std::unique<...>>
- 从自定义对象- std:unique的向量中消除重复项会导致崩溃
- 我能保证std::unique将保留第一个元素吗?
- 在 std::vector<std::unordered_set上使用 std::unique(<T>>