Future is not returning reference to value in C++

  Kiến thức lập trình

I’ve just started learning multi-threading in C++ and following this excellent tutorial.

However when I print the memory address of the string being returned in Future I’m getting a different address.

Here’s my code.

#include<iostream>
#include <thread>
#include <future>
#include <string>

void thFunc(std::promise<std::string> && prms) {
  std::string str("Hello from future ^^");
  std::cout << "Location=" << (void*)str.data() << "n";
  prms.set_value(str);
}

int main() {
  std::promise<std::string> prms;
  std::future<std::string> ftr = prms.get_future();
  std::thread th(&thFunc, std::move(prms));
  std::printf("Hello from main!!n");

  std::string futStr = ftr.get();
  std::cout << futStr << "t Location= " << (void*)futStr.data() << "n";
  th.join();
  return 0;
}

How I’m compiling it:

clang++ -g -Wall -std=c++11 -stdlib=libc++ -o future_ex future_ex.cpp

And here’s the output that I’m getting:

Hello from main!!
Location=0x30cdbff01
Hello from future ^^     Location= 0x30cd3dfa1

I checked the documentation of get() and it does uses std::move which means that there’s no copy in between. So not sure why address is different.

Any help/explanation on this behaviour would be great 🙂
Please let me know if more info is needed.

1

LEAVE A COMMENT