这个 C++ 程序中发生了什么?
What is happening here in this C++ program?
我正在阅读这篇优秀的文章 Uses & Abuses of Access Rights。我不明白下面的例子。
文件:x.h
class X
{
public:
X() : private_(1) { /*...*/ }
template<class T>
void f( const T& t ) { /*...*/ }
int Value() { return private_; }
private:
int private_;
};
文件:break.cpp
#include "x.h"
#include <iostream>
class BaitAndSwitch
// hopefully has the same data layout as X
{ // so we can pass him off as one
public:
int notSoPrivate;
};
void f( X& x )
{
// evil laughter here
(reinterpret_cast<BaitAndSwitch&>(x)).notSoPrivate = 2;
}
int main()
{
X x;
std::cout<<x.Value()<<'\n';
f(x);
std::cout<<x.Value()<<'\n';
}
这个程序是如何工作的?全局函数 f() 中实际发生了什么?请大神解释一下私有变量的值是如何改变的?
为什么 herb sutter 说 X 和 BaitAndSwitch 的对象布局不能保证相同,尽管实际上它们可能总是相同?
这个程序定义好吗?
铸造正在将私有区域重新映射到新结构中的 public 区域。由于未设置内部结构的布局,因此不能保证此行为有效(尽管它可能是稳定的)。
这与抓取一个指针并向其中写入内容并没有什么不同,尽管它的完成方式更精确一些。
见[http://en.cppreference.com/w/cpp/language/reinterpret_cast]
你基本上是在告诉编译器你的对象实际上是一个 BaitAndSwitch
对象,它实际上会按照你告诉它的去做:-)
我正在阅读这篇优秀的文章 Uses & Abuses of Access Rights。我不明白下面的例子。
文件:x.h
class X
{
public:
X() : private_(1) { /*...*/ }
template<class T>
void f( const T& t ) { /*...*/ }
int Value() { return private_; }
private:
int private_;
};
文件:break.cpp
#include "x.h"
#include <iostream>
class BaitAndSwitch
// hopefully has the same data layout as X
{ // so we can pass him off as one
public:
int notSoPrivate;
};
void f( X& x )
{
// evil laughter here
(reinterpret_cast<BaitAndSwitch&>(x)).notSoPrivate = 2;
}
int main()
{
X x;
std::cout<<x.Value()<<'\n';
f(x);
std::cout<<x.Value()<<'\n';
}
这个程序是如何工作的?全局函数 f() 中实际发生了什么?请大神解释一下私有变量的值是如何改变的?
为什么 herb sutter 说 X 和 BaitAndSwitch 的对象布局不能保证相同,尽管实际上它们可能总是相同? 这个程序定义好吗?
铸造正在将私有区域重新映射到新结构中的 public 区域。由于未设置内部结构的布局,因此不能保证此行为有效(尽管它可能是稳定的)。
这与抓取一个指针并向其中写入内容并没有什么不同,尽管它的完成方式更精确一些。
见[http://en.cppreference.com/w/cpp/language/reinterpret_cast]
你基本上是在告诉编译器你的对象实际上是一个 BaitAndSwitch
对象,它实际上会按照你告诉它的去做:-)