简体   繁体   English

C ++中的部分const类型转换

[英]Partial const typecast in C++

Sometimes, when passing or returning structs, it may be needed to make some of the fields const: 有时,在传递或返回结构时,可能需要使某些字段为const:

struct A
{
   char c;
   int x;
};

struct B
{
   const char c;
   int x;
};

void process(B& b)
{
   if(b.c=='1')
      b.x++;
}

void test()
{
   A a;
   a.c = '1';
   a.x = 0;
   process(reinterpret_cast<B&>(a));
}

Is this partial const typecasting portable and safe enough? 这个局部const类型转换是否可移植且安全?

没有这样的技术是不安全的,这是不确定的行为-在不相关的类型之间进行强制转换(即使它们看起来很相似)也不是安全的。

It is safe only for the sample from your code . 仅对您代码中的示例安全。 In general the technique is not safe. 通常,该技术并不安全。

The ac isn't constant in the moment of it's declaration , so Bc will inherit the c value , and the constness of c will be use only to enforce syntax. ac在声明时不是常数,因此Bc将继承c值,而c的常数将仅用于强制语法。

The problem would occur if the it was the other way around : 如果问题是相反的,则会发生此问题:

B b;
b.c = '1';
b.x = '0;
process(reinterpret_cast<A&>(b));

The reason would be that bc would be assigned to a constant at the time of declaration, and attempting to change ac could result in undefined behavior because you might end up changing a variable from a read only space. 原因是在声明时会将bc分配给常量,并且尝试更改ac可能会导致未定义的行为,因为您可能最终会从只读空间更改变量。

As pointed out by Wojtek.It is not safe clearly because of casting between 2 different types and shouldn't be used.But just for demonstration purposes as i mentioned in comment we can do chaining of typecasting for this particular case. 正如Wojtek所指出的那样,由于2种不同类型之间的转换而导致的不安全显然不应该使用,但是正如我在评论中提到的那样,仅出于演示目的,我们可以针对这种特殊情况进行类型转换的链接。

1st add constness in A's object and then use reinterpret_cast 1在A的对象中添加常量,然后使用reinterpret_cast

struct A
{
   char c;
   int x;
};

struct B
{
   const char c;
   int x;
};

void process(B& b)
{
   if(b.c=='1')
      b.x++;

      cout<<b.x;
}


void  test() {
    // your code goes here
    A a;
   a.c = '1';
   a.x = 3;
   process(reinterpret_cast<B&>(const_cast<A&>(a))); //first add constness to A's data and then use reinterpret_cast

}

it is demonstrated here. 它在这里演示。 http://ideone.com/xnblvi If anyone find any problem please comment. http://ideone.com/xnblvi如果有人发现任何问题,请发表评论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM