常量引用函数参数的地址何时唯一?

When is the address of a const reference function parameter unique?

本文关键字:何时 唯一 地址 引用 函数 参数 常量      更新时间:2023-10-16

在下面的示例代码中,我想知道对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的行为如下:

  1. 前三次调用foo打印相同的地址。
  2. foo(从线程(打印地址的最后两次调用未由前三次调用打印。
  3. 在对foo的最后两次调用中,log_cref_address打印相同的地址当且仅当从子线程调用。

在任何计算机上,这些行为中的哪一个(如果有(由C++标准保证?

都不是。该标准不保证临时变量的地址。