gpt4 book ai didi

c++ - std::vector 的 C 风格转换

转载 作者:太空宇宙 更新时间:2023-11-04 05:23:30 24 4
gpt4 key购买 nike

当我试图找到一个解决方案来转换 std::vector<Derived *> 时,我在现有代码库中偶然发现了这个实现。到 std::vector<Base *> .我正在使用 C++11。

考虑以下代码片段:

#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;
}

感觉非常狡猾,所以我试图找到一个替代方案。 This post建议使用 std::vector::assign 的方法.所以现在, 我的主要功能如下所示:

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;
}

它按预期编译和工作。现在我有以下问题:

1) 为什么第一个片段甚至可以编译但使用 static_cast导致编译错误?

2) 这两种方法的计算成本是多少?我预计第二个会因创建临时 vector 对象而产生额外费用 new_vec , 但我不确定。

3) 在这些情况下使用 C 风格转换的缺点是什么?

谢谢。

最佳答案

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

因为 C 型类型转换是一把大锤,会把所有的谨慎都抛到九霄云外。它的座右铭是“你想要它?你得到它”,而不管“它”是什么。静态转换只会执行在静态类型检查方面正确的转换。

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.

您的期望是正确的。但是具有明确语义的代码的成本可能会增加程序的工作量。

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

它将始终编译,并且在您尝试在未来的某个平台上运行它之前,您不会发现有问题。因为今天它可能有用。

关于c++ - std::vector 的 C 风格转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46326947/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com