常量引用函数参数的地址何时唯一?
When is the address of a const reference function parameter unique?
在下面的示例代码中,我想知道对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++标准保证?
都不是。该标准不保证临时变量的地址。
相关文章:
- 何时在引用或唯一指针上使用移动语义
- C++优先级队列,按对象的唯一指针的特定方法升序排列
- 计算排序向量的向量中唯一值的计数
- 何时提供默认参数作为模板参数
- 如何使用Visual Studio 2017在C++中为参数化对象数组使用唯一指针
- C++-明确何时以及如何调用析构函数
- 通过组合不同的类型来创建唯一的id
- 使用Unique_ptr确保工厂中的对象唯一
- c++多进程编写一个唯一的文件
- 在以唯一ptr为值的C++映射中,动态内存何时会被销毁
- 如何更改唯一指针向量的可见性
- 在C++的两个字符串中连接以逗号分隔的唯一值
- 何时应通过引用传递矢量参数而不是按值传递矢量参数?
- 共享指针和具有自定义删除程序的唯一指针之间的语法差异背后的任何原因
- C++尝试深度复制唯一指针时出现内存访问冲突
- 具有引用成员的结构是否具有唯一的对象表示形式
- 使用 RTTI 克隆唯一指针的向量
- 常量引用函数参数的地址何时唯一?
- 唯一_ptr何时在此设置器上重置
- 获取唯一编号并知道它们何时被释放