c++ - C ++ 11访问类内存变量是否具有本地副本
问题描述
我对 c++11 库不是很熟悉,thread
我对以下演示有两个问题。在这个演示中,我想使用更改值功能来修改公共成员变量数据。
- 第一个问题是我得到如下编译错误。
- 二是想知道C++处理这种情况的原理。我感到困惑的是,每个线程是否会为数据变量创建本地副本然后访问它。
class TestThread
{
private:
int *data;
void changeValue(unsigned int index)
{
if (index >= 10000)
return;
data[index] = 1;
}
public:
TestThread()
{
data = new int[10000];
}
void createThread()
{
const int numThread = 2;
std::vector < std::thread > threadsPool;
for (unsigned int i = 0; i < numThread; ++i)
{
threadsPool.emplace_back(&TestThread::changeValue, i);
}
for (unsigned int i = 0; i < numThread; ++i)
{
threadsPool[i].join();
}
}
void outputResult()
{
std::cout << "data valuve " << std::endl;
std::cout << data[0] << std::endl;
std::cout << data[1] << std::endl;
}
TestThread(const TestThread& t) {
std::cout << "Calling constructor" << std::endl;
}
~TestThread()
{
delete[] data;
}
};
int main() {
TestThread testclass;
testclass.outputResult();
testclass.createThread();
testclass.outputResult();
return 0;
}
编译错误如下
testThread.cpp:21:58: required from here
/usr/include/c++/7/thread:240:2: error: no matching function for call to ‘std::thread::_Invoker<std::tuple<void (TestThread::*)(long unsigned int), unsigned int> >::_M_invoke(std::thread::_Invoker<std::tuple<void (TestThread::*)(long unsigned int), unsigned int> >::_Indices)’
operator()()
^~~~~~~~
/usr/include/c++/7/thread:231:4: note: candidate: template<long unsigned int ..._Ind> decltype (std::__invoke((_S_declval<_Ind>)()...)) std::thread::_Invoker<_Tuple>::_M_invoke(std::_Index_tuple<_Ind ...>) [with long unsigned int ..._Ind = {_Ind ...}; _Tuple = std::tuple<void (TestThread::*)(long unsigned int), unsigned int>]
_M_invoke(_Index_tuple<_Ind...>)
testThread.cpp:21:58: required from here
/usr/include/c++/7/bits/invoke.h:89:5: error: no type named ‘type’ in ‘struct std::__invoke_result<void (TestThread::*)(unsigned int), unsigned int>’
解决方案
推荐阅读
- javascript - Yii2:如果选择值不是 promtp,则更改 div 的类
- input - 尝试制作 NDI 网络摄像头输入(虚拟输入)的第二个实例
- delphi - 使用 Delphi 的 HTML5 画布动画
- reactjs - 反应条件渲染
- mysql - Mysql - 带有重音符号的 Concat 字符串会导致格式错误的字符
- javascript - Firefox中的D3升高和降低svg元素不起作用
- amazon-web-services - 使用 ARN 创建 aws s3clinet 时出现问题,承担 s3 存储桶的角色
- javascript - 角度导航问题
- c# - 为 Axis2 Web 服务创建客户端时对传输和消息使用不同的证书
- javascript - Vue.js:如何更改 Vue2-slider 组件的颜色