const char&作为函数的参数

Row*_*era 1 c++ linux multithreading boost pointers

我需要对以下代码块进行一些澄清.我正在研究类似编码的东西,我想了解它是如何工作的.谷歌上没有太多的提及,我发现的唯一一个技术太难以理解了.

  1. 在以下代码中,线程和非线程函数具有不同的输出.这是为什么?

    #include <boost/thread.hpp>
    #include <iostream>
    #include <stdio.h>
    
    using namespace std;
    
    void fTry1(const char&);
    void fTry2(const char&);
    
    int main()
    {
      boost::thread tTry1, tTry2;
      const char *a = "efgh";
    
      tTry1 = boost::thread(fTry1, *a);
      fTry2(*a);
      tTry1.join();
    
      return 0;
    }
    
    void fTry1(const char& a)
    {
      cout << "Thread" << endl;
      cout << &a << endl;
    }
    
    void fTry2(const char& a)
    {
      cout << "Non-thread" << endl;
      cout << &a << endl;
    }
    
    Run Code Online (Sandbox Code Playgroud)

样本输出:

Non-thread
efgh
Thread
e<garbage data>
Run Code Online (Sandbox Code Playgroud)
  1. 如果我改变以下行

    cout << &a << endl;
    
    Run Code Online (Sandbox Code Playgroud)

    cout << a << endl;
    
    Run Code Online (Sandbox Code Playgroud)

输出变得类似

Non-thread
e
Thread
e
Run Code Online (Sandbox Code Playgroud)

再次,为什么?

-

我正在使用的代码使用数字2,但传递的字符串是文件夹的路径,所以我想要整个字符串,而不仅仅是第一个字符.但由于我不明白它是如何工作的,我将无法轻易地对其进行更改.

Jts*_*Jts 6

默认情况下,传递给的参数boost::thread将被"捕获" value.要捕捉它们reference,你必须使用 boost::ref;

tTry1 = boost::thread(fTry1, boost::ref(*a));
Run Code Online (Sandbox Code Playgroud)

这与lambda函数非常相似,例如:

const char *a = "efgh";
const char &c = *a;

auto garbage = [c]() { // c captured by value
   cout << &c << endl;
};

auto works = [&c]() { // c captured by ref
    cout << &c;
};

garbage();
works();
Run Code Online (Sandbox Code Playgroud)

注意:

小心传递referencespointers新线程,因为您需要确保它们在新线程使用时保持有效.但是,在您的独特情况下,这不适用,因为字符串文字efgh具有static duration这样的安全性.