C++参数是一个指向常量对象的指针,但更新后的对象没有返回?
我有本机 C++ 类 SrcClass
包含以下内容:
std::vector<shotEntry> objectsQueue;
bool getRelatedEntry(const entryToProcess *entriesDeets, int &i) const {
if (i >= (int)objectsQueue.size()) {
i = 0;
return false;}
if (!objectsQueue.size()) return false;
entriesDeets = &(objectsQueue[i++]);
return true;
}
在我的客户端中,我有:
const entryToProcess *entriesDeets = NULL;
int i = 0;
while (srcObj->getRelatedEntry(entriesDeets, i)) {
当我单步执行 getRelatedEntry
形式参数时,entriesDeets
更新为预计返回前。当它返回时,客户端的实际参数不会更新。
这是我离开两个月后回到的一个大项目。我很确定我所做的最后一次重构是引入了这些可恶的向量
。当我搞乱标题时,需要很长时间才能编译。我是否对 C# 的初始化一次/只读/常量感到困惑?我可以让客户端取回只读本机对象吗?
I have native C++ class SrcClass
containing the following:
std::vector<shotEntry> objectsQueue;
bool getRelatedEntry(const entryToProcess *entriesDeets, int &i) const {
if (i >= (int)objectsQueue.size()) {
i = 0;
return false;}
if (!objectsQueue.size()) return false;
entriesDeets = &(objectsQueue[i++]);
return true;
}
In my client I have:
const entryToProcess *entriesDeets = NULL;
int i = 0;
while (srcObj->getRelatedEntry(entriesDeets, i)) {
When I step through getRelatedEntry
the formal parameter, entriesDeets
is updated as expected before returning. When it returns the actual parameter of the client is not updated.
This is in some big project I have returned to after two months away. I'm pretty sure the last refactoring I did was to introduce these damnable vectors
. It takes ages to compile when I mess with headers. Am I getting confused with the initialize once/ readonly/ const'ness of C#? Can I get away with the client getting a read only native object back?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是因为您正在设置函数参数的值。你想要:
和
This is because you are setting the value of the function's parameter. You want:
and
EntryDeets 是 getRelatedEntry 内的局部变量。您只修改了本地,并没有影响传入的值。您需要传递对指针的引用或对指针的指针。
entriesDeets is a local variable inside getRelatedEntry. You only modified the local, you didn't affect the value passed in. You need to pass a reference to pointer or a pointer to pointer.
指针被更新,但它是函数内部的内部副本。如果您希望该更改在函数外部可见,您应该传递一个引用:
或者在 C 风格中传递一个双指针,并在每次使用时在内部取消引用它:
The pointer is updated, but it is the internal copy inside the function. If you want that change to be visible outside of the function, you should pass a reference:
Or in C style a double pointer and dereference it internally on every usage: