antogilbert antogilbert - 1 month ago 7
C Question

C-style cast of std::vector

I stumbled upon this implementation in an existing code base when trying to find a solution to casting an

std::vector<Derived *>
to a
std::vector<Base *>
. I am using C++11.

Consider the following code snippet:

#include <iostream>
#include <vector>

class A
{
// some implementation details
};

class B : public A
{
// some implementation details
};

void count(std::vector<A *> const & a_vec)
{
std::cout << "IT HAS THESE MANY PTRS: " << a_vec.size() << std::endl;
}

int main()
{
B * b;

std::vector<B *> b_vec {b};
count((std::vector<A *> &) b_vec);

return 0;
}


It felt extremely dodgy and so I tried to find an alternative. This post suggested an approach using
std::vector::assign
. So now,
my main function would look like this:

int main()
{
B * b;

std::vector<B *> b_vec {b};
std::vector<A *> new_vec;
new_vec.assign(b_vec.begin(), b_vec.end());
count(new_vec);

return 0;
}


It compiles and works as expected. Now I have the following questions:

1) Why does the first snippet even compile but using a
static_cast
causes a compilation error?

2) What is the computational cost of the two methods? I expect the second one to incur into extra costs due to creating the temporary vector object
new_vec
, but I am not sure.

3) What are the drawbacks of using the C-style cast in these cases?

Thanks.

Answer Source

Why does the first snippet even compile but using a static_cast causes a compilation error?

Because a C-style cast is a sledgehammer that will throw all caution to the wind. Its motto is "you want it? you got it", regardless of what "it" is. A static cast will only do a cast that is correct in terms of static type checking.

What is the computational cost of the two methods? I expect the second one to incur into extra costs due to creating the temporary vector object new_vec, but I am not sure.

Your expectation is correct. But the cost of code with well defined semantics can be in added work for the program.

What are the drawbacks of using the C-style cast in these cases?

That it will always compile, and you won't find out there's a problem until you try to run it, on some platform in the future. Because it may work today.