在下面的示例代码中,我想知道两个调用何时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;
}
在我的机器上,main
打印
foo<0>: 0x7fff7cf5507c 0x7fa0585b5e1c 0x196fc28
foo<0>: 0x7fff7cf5507c 0x7fa0585b5e1c 0x196fc28
foo<1>: 0x7fff7cf5507c 0x7fa0585b5e1c 0x196fc28
lambda: 0x7fa0585b5dcc 0x7fa057db4e1c 0x7fa0500008c8
bind(): 0x7fa0585b5d1c 0x7fa057db4e1c 0x7fa0500008c8
从许多这样的输出中,我观察到其main
行为如下:
- 前三个调用
foo
打印相同的地址。 - 最后两次调用
foo
(来自线程)打印前三个调用未打印的地址。 - 在对 的最后两次调用中
foo
,log_cref_address
当且仅当从子线程调用时打印相同的地址。
在任何机器上,哪些行为(如果有)是由 C++ 标准保证的?