#include <utility>
class A {
int* ptr;
public:
A() {
ptr = new int[10];
}
A(A&& rhs) {
this->ptr = rhs.ptr;
rhs.ptr = nullptr;
}
~A() {
if (ptr) delete[] ptr;
}
};
int main() {
A a1;
A a2;
a2 = std::move(a1);
}
Run Code Online (Sandbox Code Playgroud)
GCC 11 抱怨复制赋值运算符被删除:
<source>: In function 'int main()':
<source>:23:22: error: use of deleted function 'constexpr A& A::operator=(const A&)'
23 | a2 = std::move(a1);
| ^
<source>:3:7: note: 'constexpr A& A::operator=(const A&)' is implicitly declared as deleted …Run Code Online (Sandbox Code Playgroud) 我有一个非常简单的代码:
#include <string>
#include <iostream>
int main() {
std::string s("abc");
std::cout << s;
}
Run Code Online (Sandbox Code Playgroud)
然后,我编译了它:
g++ -Wall test_string.cpp -o test_string -std=c++17 -O3 -g3 -ggdb3
Run Code Online (Sandbox Code Playgroud)
然后将其反编译,最有趣的部分是:
00000000004009a0 <_ZNSs4_Rep10_M_disposeERKSaIcE.isra.10>:
4009a0: 48 81 ff a0 11 60 00 cmp rdi,0x6011a0
4009a7: 75 01 jne 4009aa <_ZNSs4_Rep10_M_disposeERKSaIcE.isra.10+0xa>
4009a9: c3 ret
4009aa: b8 00 00 00 00 mov eax,0x0
4009af: 48 85 c0 test rax,rax
4009b2: 74 11 je 4009c5 <_ZNSs4_Rep10_M_disposeERKSaIcE.isra.10+0x25>
4009b4: 83 c8 ff or eax,0xffffffff
4009b7: f0 0f c1 47 10 lock xadd …Run Code Online (Sandbox Code Playgroud) 我正在阅读有关内存过度使用的页面,其中提到
The C language stack growth does an implicit mremap. If you want absolute
guarantees and run close to the edge you MUST mmap your stack for the
largest size you think you will need. For typical stack usage this does
not matter much but it's a corner case if you really really care
Run Code Online (Sandbox Code Playgroud)
当程序编译时(例如通过gcc),定义了堆栈的大小限制(我记得有一个gcc参数可以调整它)。然后,在程序内部,我们可以继续在堆栈上分配。
几个问题:
mremap()会在幕后调用?为什么如果在编译时就定义了堆栈的大小限制呢?mmap堆栈呢?鉴于 x86 具有强大的内存模型,是否有必要使用std::memory_order_acquirefence(不是 operation)?
例如,如果我有这个代码:
uint32_t read_shm(const uint64_t offset) {
// m_head_memory_location is char* pointing to the beginning of a mmap-ed named shared memory segment
// a different process on different core will write to it.
return *(uint32_t*)(m_head_memory_location + offset);
}
....
int main() {
uint32_t val = 0;
while (0 != (val = shm.read(some location)));
.... // use val
}
Run Code Online (Sandbox Code Playgroud)
我真的需要std::atomic_thread_fence(std::memory_order_acquire)在return语句之前吗?
我觉得没有必要,因为上面代码的目标是尝试从 读取前 4 个字节m_head_memory_location + offset,因此重新排序栅栏后的任何内存操作都不会影响结果。
或者有一些副作用使获取栅栏变得必要?
在 x86 上是否需要获取栅栏(不是操作)? …