簡體   English   中英

副作用不起作用

[英]Side-effect not working

我創建了一個用於網絡的緩沖區類,並且使用了副作用來獲取緩沖區指針以及大小。 我創建了一個簡單的測試,該測試顯示與類的getptr()函數相同的行為。

char SomeBuffer[100];

void* getbuf(int& size) {
  size = 100;    
  return SomeBuffer;
}

int testrecv(void* ptr, int size) {
 int i = 0;//BREAKPOINT HERE
 return 0;
}

int main(int argc, char**argv) {
 int size;
 testrecv(getbuf(size), size);
}

當我從testrecv()函數中查看變量時,大小是一些留在堆棧上的隨機值。 由於getbuf()的副作用,testrecv()中的大小不應該為100嗎?

函數參數的求值順序是實現定義的 這意味着你不能依靠getbuf之前,被稱為size傳遞參數testrecv

對於您的特定編譯器,這里發生的是testrecv參數從最后到第一個被求值。 首先對size進行評估,當時它具有未指定的值(隨機值) 只有這樣, getbufgetbuf進行求值,將您的size變量修改為期望的值,但是對於函數參數來說為時已晚。

函數參數的求值順序未指定。 看來,您正在使用的系統首先評估size然后評估getbuf(size) 結果,該參數沒有期望值。 最簡單的解決方法可能是同時返回指針和大小:

std::pair<void*, int> getbuf() { return std::make_pair(someBuffer, 100); }
int testrcv(std::pair<void*, int> buffer) { ... }

(或者您可以使用適當類型的std::vector<T> ...)

問題是您正在接受評估:

testrecv(getbuf(size), size);

// What seems to be happening is
1) size is evaluated and set up for the function call.
2) getbuf() is called. This sets the local copy of size
   but the value that is being passed to the function call has already been
   evaluated. So this value will not be passed (but the random value that
   was in the variable at the time the `size` parameter was evaluated).
3) Function testrecv() called.

不要依賴副作用。

 int size;
 void* buf = getbuf(size);  // Now size will be set
 testrecv(buf, size);

參見: https : //stackoverflow.com/a/367663/14065

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM