Search code examples
c++shared-ptr

Get the last element from a std::vector


In the following example, I would like to get an element from my vector. But I don't understand the error:

#include <vector>
#include <memory>


using namespace std;

class Foo{
    virtual int end() = 0;
};

class Bar : public Foo{
    int end(){
        return 0;
    }
};


int main(){
    vector<shared_ptr<Foo>> a;
    a.push_back(make_shared<Bar>());
    shared_ptr<Foo> b = a.pop_back();
}

Here the error:

 g++ test.cpp
test.cpp: In function ‘int main()’:
test.cpp:21:35: error: conversion from ‘void’ to non-scalar type ‘std::shared_ptr<Foo>’ requested
   21 |     shared_ptr<Foo> b = a.pop_back();
      |                         ~~~~~~~~~~^~

Solution

  • This is indeed confusing. As said kiner_shah in his comment. You don't want to use pop_back

    int main(){
        vector<shared_ptr<Foo>> a;
        a.push_back(make_shared<Bar>());
        shared_ptr<Foo> b = a.back();
    }
    

    The pop_back method doesn't return anything.