0

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;
}
Sharon
  • 21
  • 2
  • Is `string_view` valid after destruction of `buffer`? Just use `vector`. And there is no need of `shared_ptr`. – ikh Sep 24 '20 at 03:01
  • The problem is it isn't my whole code - so if want to change it to `vector` i would have to change most of my headers and classes........ – Sharon Sep 24 '20 at 03:09
  • 1
    That is the right way I think. `container>` is nonsense, at least in your code. – ikh Sep 24 '20 at 03:11
  • If you really cannot change, put strings into another place (like `vector`) and enqueue the reference to this place. Remove the element at dequeue – ikh Sep 24 '20 at 03:13
  • Yep - in this code you are right. My problem is that it is neccesery in my real code, so it would take me ALOT of time to change it to 'vector>'. Dont you think there is another way doing it with 'view_string'? I mean, with the temprary 'const char*' it works so I guess there is a way doing it. – Sharon Sep 24 '20 at 03:19
  • You also can make custom deleter for `shared_ptr` removing the original string element in the `vector` object. Btw, why did you use `shared_ptr` in your real code? – ikh Sep 24 '20 at 03:24
  • Well, for some reason when I gave a struct which contains `std::string` as parameter to a fuction it was not copied correctly, but when I used `string_view` it did. So I just continued to use `std::string_view` until I got stuck with this bug. – Sharon Sep 24 '20 at 04:47

0 Answers0