【问题标题】:When is the address of a const reference function parameter unique?const 引用函数参数的地址何时是唯一的?
【发布时间】:2018-08-06 22:42:31
【问题描述】:

在下面的示例代码中,我想知道对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++ 标准在任何机器上都保证了这些行为中的哪些(如果有)?

【问题讨论】:

    标签: c++ cross-platform stack-memory addressof pass-by-const-reference


    【解决方案1】:

    没有。标准不保证临时变量的地址。

    【讨论】:

    • 特别是它不保证延长临时变量的生命周期。
    猜你喜欢
    • 2013-04-18
    • 1970-01-01
    • 2012-02-25
    • 1970-01-01
    • 1970-01-01
    • 2016-04-03
    • 2010-09-13
    • 1970-01-01
    • 2013-11-08
    相关资源
    最近更新 更多