c++ - std::vector 内存操作的安全性

标签 c++ casting

我有以下代码

size_t returnSize(const char* s)
{
       string string(s);
       return string.size();
};

size_t returnSize(const int& i)
{
       return sizeof(i);
};


template<typename T>
vector<char> Serialize(const T& t)
{
    T* pt = new T(t);
    vector<char> CasttoChar;

    for (int i =0 ;i<returnSize(t);i++)
    {
        CasttoChar.push_back(reinterpret_cast<const char*>(pt)[i]);
    }
    delete pt;
    return CasttoChar;
};
template<typename T>
T DeSerialize(const vector<char> cstr)
{
    T* a = (T*)(&cstr[0]);

    return *a;
}

int _tmain(int argc, _TCHAR* argv[])
{
    int x = 97;
    vector<char> c = Serialize(x);
    cout << DeSerialize<int>(c) << endl;

    string k = "blabla";
    vector<char> c3 = Serialize(k.c_str());
    cout << DeSerialize<const char*>(c3) << endl;

    system("PAUSE");
    return EXIT_SUCCESS;
}

//output is 
//97
//blabla

这条线是T* a = (T*)(&cstr[0]);安全的?

此外,我尝试了 reinterpret_cast<T*>(&cstr[0]);而不是 T* a = (T*)(&cstr[0]);但是编译器提示无法将 const char* 转换为 int*。那么为什么 C 风格转换有效?

最佳答案

引用标准

为什么 reinterpret_cast 失败?

5.2.10 Reinterpret cast [expr.reinterpret.cast]

The reinterpret_cast operator shall not cast away constness (5.2.11). An expression of integral, enumeration, pointer, or pointer-to-member type can be explicitly converted to its own type; such a cast yields the value of its operand.

我应该使用 C Cast 吗? 不。使用 C Cast 而不是 C++ Cast 总是不安全的。您正在尝试删除作为 UB 的对象的常量性。 使用 reinterpret_cast,实际上会捕获此错误,并在编译时告知您潜在的陷阱。

在这种情况下,您实际上应该使用 const_cast。这是将 const 对象转换为非 const 对象的唯一合法方法

但为什么 C Cast 有效

引自问题 When should static_cast, dynamic_cast and reinterpret_cast be used? 的已接受答案

A C-style cast is defined as the first of the following which succeeds:

const_cast
static_cast
static_cast, then const_cast
reinterpret_cast
reinterpret_cast, then const_cast

幸运的是,它首先尝试了 const_cast

关于c++ - std::vector 内存操作的安全性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14302168/

相关文章:

c++ - 将值传递给着色器的问题

C 运算符结果类型

c++ - 与正方形网格的最佳线相交

java - 为什么 Java 的 +=、-=、*=、/= 复合赋值运算符不需要将 long 转换为 int?

c++ - 猜数字游戏

c++ - 使用 std::map [] 运算符交换与分配(const 问题)

c++ - C/C++ 指针技巧(保存指向 int 的指针,并翻译回来)

java:结合了instanceof和cast?

c++ - 我可以在 uclibc linux 上使用 boost 吗?

c++ - 扩展 Eigen 库以包含排序