Search code examples
c++vectorshared-ptrsmart-pointersunique-ptr

Vector and smart_pointer. I don't get the actual numbers


I have this code:

#include <iostream>
#include <memory>
#include <vector>

class Test {
private:
    int data;
public:
    Test() : data{} { std::cout << "\tctor Test(" << data << ")\n"; }
    Test(int data) : data{ data } {
        std::cout << "\tctor Test(" << data << ")\n";
    }
    int get_data() const { return data; }
    ~Test() { std::cout << "\tdtor Test(" << data << ")\n"; }
};


std::unique_ptr<std::vector<std::shared_ptr<Test>>> make() {

    std::unique_ptr<std::vector<std::shared_ptr<Test>>> ptr = std::make_unique<std::vector<std::shared_ptr<Test>>>();

    return ptr;
}

void fill(std::vector<std::shared_ptr<Test>>& vec, int num) {

    for (int i = 1; i <= num; i++) {

        std::cout << "Number " << i << ": " <<std::endl;
        int a;
        std::cin >> a;

        std::shared_ptr<Test> ptr(new Test(a));
        vec.push_back(std::move(ptr));
    }
}

void display(const std::vector<std::shared_ptr<Test>>& vec) {

    
    for (unsigned i = 0; i < vec.size(); i++)
    {
        
        std::cout << vec[i] << std::endl;
    }
}

int main()
{
    std::unique_ptr<std::vector<std::shared_ptr<Test>>> vec_ptr;
    vec_ptr = make();
    std::cout << "How many data points: ";
    int num;
    std::cin >> num;
    fill(*vec_ptr, num);
    display(*vec_ptr);
    return 0;

}

I want to print out my vector with the display function, but I only get the adress. I only got something like this:

How many data points: 3
 Number 1:
 1
         ctor Test(1)
 Number 2:
 2
         ctor Test(2)
 Number 3:
 3
         ctor Test(3)
 014A5820
 014A5850
 014A9460
         dtor Test(1)
         dtor Test(2)
         dtor Test(3)

How do i get the actual numbers? Can someone please tell me what I do wrong.


Solution

  • Your Test class has the get_data() function to get the number, so use that.

    Changing the line

    std::cout << vec[i] << std::endl;
    

    to

    std::cout << vec[i] << " : " << vec[i]->get_data() << std::endl;
    

    will give you something like this:

    0x18f4190 : 1
    0x18f41f0 : 2
    0x18f41d0 : 3