Как превратить vectror<A*> в const vectror<const A*>?
Работает и создание нового вектора, и reintrtpret_cast.
Насколько он безопасен в данном случае?
#include <vector>
#include <memory>
#include <iostream>
using namespace std;
class A
{
int n = 1;
public:
explicit A(int nn)
:n(nn){}
~A(){}
void foo()
{
cout << "A:" << n << endl;
}
void foo() const
{
cout << "A const:" << n << endl;
}
};
class B
{
vector<shared_ptr<A>> vspa;
public:
B()
{
for (auto& i : { 1,2,3,4,5,6,7,8,9,10 })
{
vspa.push_back(make_shared<A>(i));
}
}
~B(){}
const vector<shared_ptr<const A>> get_vspca() const
{
return vector<shared_ptr<const A>>(vspa.begin(), vspa.end());
//safe, require vector construction and shared_ptr ref_count++
}
const vector<shared_ptr<const A>>& get_crvspca() const
{
return reinterpret_cast<const vector<shared_ptr<const A>>&>(vspa);
//unsafe(?) but transparent
}
};
void bar(const vector<shared_ptr<const A>>& vv)
{
for (auto& i : vv)
{
i->foo();
cout << "^use_count: " << i.use_count() << endl;
}
cout << "======" << endl;
}
int main(int argc, char* argv[])
{
const B bb;
bar(bb.get_vspca());
bar(bb.get_crvspca());
return 0;
}