通过unique_ptr访问结构成员会产生分段错误 [英] Accessing struct member through unique_ptr gives segmentation fault
问题描述
这就是我将指针设置为struct的方式.在运行时,分段错误在第二行引发.LoadedPDFInfo是Canvas命名空间中的结构
This is how I set pointer to struct. At runtime segmentation fault is thrown at second line. LoadedPDFInfo is struct in Canvas namespace
struct std::unique_ptr<Canvas::LoadedPDFInfo> pdfInfo;
pdfInfo->handle = ++currentPDFHandle;
pdfInfo->totalPageNum = FPDF_GetPageCount(doc);
推荐答案
首先, std :: unique_ptr
是 class
而不是 struct
,因此请删除 pdfInfo
变量声明上的 struct
前缀.您可能正想着这个:
First, std::unique_ptr
is a class
not a struct
, so get rid of the struct
prefix on the pdfInfo
variable declaration. You were probably thinking of this instead:
std::unique_ptr<struct Canvas::LoadedPDFInfo> pdfInfo;
但是,即使使用实际的 struct
类型声明变量(或类型转换),您仍然不需要 struct
前缀.C需要,而C ++不需要.
But even when declaring variables (or type-casting) using actual struct
types, you still do not need the struct
prefix. C needs that, C++ does not.
第二,发生段错误是因为您仅声明了 pdfInfo
变量,但实际上并未指向有效的 LoadedPDFInfo
对象,因此请使用->
运算符无效.就像常规指针一样, std :: unique_ptr
(以及 std :: auto_ptr
和 std :: shared_ptr
)必须指向进入某事,以便访问该某事的成员.例如:
Second, your segfault is happening because you have merely declared the pdfInfo
variable, but it is not actually pointing at a valid LoadedPDFInfo
object, so using the ->
operator is not a valid operation. Just like a regular pointer, std::unique_ptr
(and std::auto_ptr
, and std::shared_ptr
) have to point at something in order to access that something's members. For example:
std::unique_ptr<Canvas::LoadedPDFInfo> pdfInfo(new Canvas::LoadedPDFInfo);
这篇关于通过unique_ptr访问结构成员会产生分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!