[英]Pointer to a std::vector object(s)
I need to do the following:我需要执行以下操作:
std::vector<std::string> A;
std::vector<std::string> B;
==> pointer_to_vector<std::string> ptr;
//Some Code
ptr = A; //ptr points to object A
//Some More Code
ptr = B; // //ptr points to object B
During the program, ptr
needs to refer to both A
and B
at different times.在程序中,
ptr
需要在不同的时间同时引用A
和B
How would it be implemented and considering that std::vector
makes reallocations, how to use smart pointers here?它将如何实现并考虑到
std::vector
进行重新分配,如何在此处使用智能指针?
You define a pointer to a vector the same way you define a pointer to any other type - using *
in the pointer declaration, and the &
address-of operator to get the memory address of a variable to assign to the pointer, eg:您可以像定义指向任何其他类型的指针一样定义指向向量的指针 - 在指针声明中使用
*
,并使用&
address-of 运算符获取要分配给该指针的变量的内存地址,例如:
std::vector<std::string> A;
std::vector<std::string> B;
std::vector<std::string> *ptr;
//Some Code
ptr = &A; //ptr points to object A
//Some More Code
ptr = &B; // //ptr points to object B
Or, use std::addressof()
, if any objects overload operator&
for their own purposes (which std::vector
does not), eg:或者,使用
std::addressof()
,如果任何对象出于自己的目的重载operator&
( std::vector
没有),例如:
//Some Code
ptr = std::addressof(A); //ptr points to object A
//Some More Code
ptr = std::addressof(B); // //ptr points to object B
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.