美文网首页
static_cast caution

static_cast caution

作者: 疾风2018 | 来源:发表于2024-03-16 22:47 被阅读0次

static_cast caution

It is likely to lead unexpected behavior and maybe dangerous to invoke static_cast on wrong C++ object. Below example demostrates it.

On the second invocation of foo, foo(d2), the instance of class D2 is casted into instance of class D1 and the memory address for access to member variable b of D1 is calculated as d2's address + offset of b. The resulted address is actually out of the available memory of instance d2 because d2 is instance of class D2 which is smaller than class D1(D1 has a big member variable arr). That causeses unexpected behavior: if the memory which the address points is already allocated to the current process, the wrong data(the memory is occupied by another objects or values) are read; otherwise a "memory access violation" exception occurs.

#include <iostream>
#include <array>

using namespace std;

class Base
{
public:
    virtual void say()
    {
        cout << "hello, base;" << endl;
    }
};

class D1 : public Base
{
public:
    char a = '*';
    std::array<char, 10000> arr{};
    char b = '+';

public:
    void say() override
    {
        cout << "hello, D1;" << a << endl;
    }

    void jump()
    {
        cout << "jump " << b << endl;
    }
};

class D2 : public Base
{
public:
    long long v = 7777;

public:
    void say() override
    {
        cout << "hello, D2;" << v << endl;
    }
};

void foo(Base & bb);

int main()
{
    D1 d1;
    D2 d2;
    foo(d1);
    foo(d2); // cause memory access violation!!!
}

void foo(Base& bb)
{
    D1& d = static_cast<D1&>(bb);
    d.jump();
}

In my experiment, the "memory access violation" exception happens.
<img width="851" alt="image" src="https://github.com/Alex-Cheng/alex-cheng.github.io/assets/1518453/7123bf97-4948-4cf5-866a-a271fe3cfd94">

相关文章

  • 类型转换

    类型转换: static_cast static_cast:static_cast < type-id > ( e...

  • lust ,caution

    很多事情的发生猝不及防,但是有始就有终。第一个问题是问你考哪个学校,原来最后一个问题还是这个。我想这是最好的安排吧...

  • Lust, Caution

    李安太厉害了。 我想,只有在李安的镜头下,这部电影才有可能呈现为它最后的这个样子。私以为,李安可以说是导演界的钱钟...

  • raz_lb_table of content

    After SchoolAll By MyselfAnimal Caution SignsAnimal Cover...

  • 四级积累

    Be capable of 能够,有能力 Be caution of 谨防 Have the advantage ...

  • 第二十六章

    Mrs. Gardiner's caution to Elizabeth was punctually and k...

  • C++中static_cast和dynamic_cast强制类型

    一、static_cast关键字(编译时类型检查) 用法:static_cast < type-id > ( ex...

  • ITEM 86: 实现SERIALIZABLE时要非常小心

    ITEM 86: IMPLEMENT SERIALIZABLE WITH GREAT CAUTION  允许序列化...

  • C++ static_cast、const_cast、reint

    一. static_cast static_cast基于内容转换,相对安全。 1.普通用法 2.void* 转换 ...

  • C++面试题整理

    C++基础部分 C++ static_cast和dynamic_cast的区别 static_cast可以部分的做...

网友评论

      本文标题:static_cast caution

      本文链接:https://www.haomeiwen.com/subject/xzcozdtx.html