Tay*_*ols 0 c++ cross-platform addressof stack-memory pass-by-const-reference
在下面的示例代码中,我想知道两次调用log_cref_address何时可靠地打印相同的地址.
#include <iostream>
#include <thread>
#include <functional>
using namespace std;
void log_cref_address(const int& t) {
cout << addressof(t) << ' ';
}
template <int i>
void foo() {
log_cref_address(i); // different if foo called from different threads
thread([] { log_cref_address(i); }).join(); // same if already in thread
thread(log_cref_address, i).join(); // same if already in thread
cout << endl;
}
int main() {
// first three calls print identical addresses
cout << "foo<0>: "; foo<0>();
cout << "foo<0>: "; foo<0>();
cout << "foo<1>: "; foo<1>();
cout << endl;
// last two from thread yields different addresses from the first three
cout << "lambda: "; thread([] { foo<0>(); }).join();
cout << "bind(): "; thread(bind(foo<0>)).join();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在我的机器上,main打印
foo<0>: 0x7fff7cf5507c 0x7fa0585b5e1c 0x196fc28
foo<0>: 0x7fff7cf5507c 0x7fa0585b5e1c 0x196fc28
foo<1>: 0x7fff7cf5507c 0x7fa0585b5e1c 0x196fc28
lambda: 0x7fa0585b5dcc 0x7fa057db4e1c 0x7fa0500008c8
bind(): 0x7fa0585b5d1c 0x7fa057db4e1c 0x7fa0500008c8
Run Code Online (Sandbox Code Playgroud)
从这样的许多输出中,我观察到的main行为如下:
foo打印相同的地址.foo(来自线程)打印的地址不是前三次调用打印的.foo,log_cref_address当且仅当从子线程调用时才打印相同的地址.在任何机器上,C++标准都保证了哪些(如果有的话)这些行为?
| 归档时间: |
|
| 查看次数: |
47 次 |
| 最近记录: |