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

标签 c++ c c++11 casting static-cast

当我试图找到一个解决方案来转换 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/

相关文章:

C++ push_back 方法

c++ - 使用 dbms_pipe 插入来自繁重事务的数据

c++ - 为什么我的鼠标光标坐标突然缩放?

c++ - 通过 Lua 获取 C++ wchar_t 到 Flash

c++ - std::result_of 因 void 返回类型而失败

c++ - boost 序列化 - 序列化 std::tr1::shared_ptr?

c - 如果已经比较了一个字符,我如何在两个 c_strings 之间进行比较检查?

c - gcc 不会在 OS X 的命令行上包含 libcurl

ios - 从 objective-c 生成 key 并使用 OpenSSL 签名创建 CSR

c++ - STL 容器元素是否明确要求 (noexcept) 可破坏?