In this code I created 2 functions in addition to the main function. One pushes an object to the queue, and the other one gets the user input and adds it to the queue as a shared pointer<string_view>.
When trying to print the user input which we added to the queue, it does not print anything. The thing is when you push shared_ptr<string_view>("Hello World!")
instead of the user input, it do prints "Hello World!"
I do understand (or thinks I do) it is related to the fact that "Hello World!" is temporary while the buffer variable is local - but I dont know how to fix that....
#include <string_view>
#include <iostream>
#include <queue>
#include <memory>
using namespace std;
void addToQueue(queue<shared_ptr<string_view>> &queue, shared_ptr<string_view> object ) {
queue.push(object);
}
void readInput(queue<shared_ptr<string_view>> &queue) {
string buffer;
//get user input
cin >> buffer;
// When changing this row to
// addToQueue(make_shared<string_view>("Hello World!"));
//"Hello World!" will be printed
addToQueue(queue, make_shared<string_view>(buffer));
}
int main() {
queue<shared_ptr<string_view>> queue;
readInput(queue);
cout << *queue.front().get() << endl;
}
Aucun commentaire:
Enregistrer un commentaire