在Visual Studio中,我们都有"baadf00d",在运行时在C++中检查调试器中的变量时看到过"CC"和"CD".
根据我的理解,"CC"仅处于DEBUG模式,以指示内存何时是new()或alloc()并且是单元化的."CD"代表删除或免费内存.我在RELEASE版本中只看过"baadf00d"(但我可能错了).
偶尔会遇到内存泄漏,缓冲区溢出等问题,这些信息会派上用场.
是否有人能够指出何时以何种模式将内存设置为可识别的字节模式以进行调试?
这两个代码段之间是否存在差异:
void f() {
thread_local vector<int> V;
V.clear();
... // use V as a temporary variable
}
Run Code Online (Sandbox Code Playgroud)
和
void f() {
static thread_local vector<int> V;
V.clear();
... // use V as a temporary variable
}
Run Code Online (Sandbox Code Playgroud)
Backstory:最初我有一个STATIC向量V(用于保存一些中间值,每次进入函数时都会被清除)和一个单线程程序.我想把程序变成多线程程序,所以我不得不摆脱这个静态修饰符.我的想法是将每个静态转换为thread_local并且不担心其他任何事情?这可能会适得其反吗?
在问题Using QSqlQuery from multiple thread中,结果是线程存储解决了问题。
我制作了一个简单的演示代码,以绝对清楚 C++11 thread_local 说明符。下面的代码创建两个线程,它们将 ThreadLocal 对象作为本地唯一对象。Storage::get 函数是线程特定的单例。标准是否保证在线程函数的连接或退出时调用 ThreadLocal 析构函数?
使用 GCC 5.4.0 编译(g++ -o main main.cpp --std=c++11 -lpthread)
#include <thread>
#include <mutex>
#include <string>
#include <chrono>
#include <iostream>
#include <atomic>
static std::mutex mtx;
struct ThreadLocal {
std::string name;
~ThreadLocal() {
mtx.lock();
std::cout << "destroy " << name << std::endl;
mtx.unlock();
}
};
struct Storage {
static ThreadLocal &get() {
/* Thread local singleton */
static thread_local ThreadLocal l;
static std::atomic<int> cnt(0);
l.name = …Run Code Online (Sandbox Code Playgroud)