线程中引用类型为什么会没用呢?

一如当初 发布于 2014/06/24 16:09
阅读 79
收藏 0

#include "stdafx.h"
#include <iostream>
#include <Windows.h>
#include <thread>

int g_num = 0;

void thread1(int &x)
{
	while (x < 3)
	{
		Sleep(2000);
		std::cout << "x = " << &x << std::endl;   // 地址和g_num的地址不同
	}
}

void test1(int &x)
{
	x = 888;
}

void test2()
{
	std::thread t1(thread1, g_num);  // 传递指针才可以,为什么引用就不行呢?
	t1.detach();
}

int _tmain(int argc, _TCHAR* argv[])
{
	int x = 5;
	test1(x);
	// x = 888
	
	test2();
	g_num = 3;
	std::cout << "Address " << &g_num << std::endl;

	system("pause");
	return 0;
}

test1()测试修改引用值没问题,test2()主要是用到了std::thread,就不行了,传递进去的变量地址都不同

加载中
0
mowind
mowind

http://www.cplusplus.com/reference/thread/thread/thread/

Fn and Args...are template parameters: if implicitly deduced, these are the proper lvalue or rvalue reference type to bind the arguments to. Note though, that on the call tofnin the new thread, decay copies offnandargs...are always used (seestd::reffor a wrapper class that makes references copyable).


一如当初
一如当初
明白了,谢谢!
返回顶部
顶部