c++ - 击败 C++ 访问资格的最干净方法是什么?

标签 c++ private

我决定通过访问内部变量来解决 GNU libstdc++ 中的错误。回想起约翰内斯在他的博客上解决了这个问题,我查了一下……但除了使用静态初始化器来完成肮脏工作的基本概念之外,无法理解代码。所以,我把它归结为这个,它非常紧凑。

但是,正如所评论的,这会导致每个翻译单元重复很少的对象和访问器函数,从而导致令人讨厌的级联。是否有一种规范的方法可以做到这一点,比如 Boost 最佳实践?

对不好的幽默表示歉意,但这并不是无缘无故的……我们不希望这段代码“工作安全”!

/* This hack installs a static initializer, so to avoid the ordering fiasco,
make one fresh copy per translation unit, via anonymous namespace. */
namespace {

template< typename T, T value, T &dest >
struct class_rape {
    class_rape() { dest = value; } // you've been raped in the class!
    static class_rape r;
};
template< typename T, T value, T &dest >
class_rape< T, value, dest > class_rape< T, value, dest >::r;


// Usage (cvt_[w]filebuf is a specialization of GCC basic_filebuf)

typedef bool cvt_filebuf::*cvt_fb_reading_t;
typedef bool cvt_wfilebuf::*cvt_wfb_reading_t;

/* Access these variables, or functions accessing them (applies recursively),
only in anonymous namespace or in non-header file, per one-definition rule. */
cvt_fb_reading_t cvt_filebuf_reading;
cvt_wfb_reading_t cvt_wfilebuf_reading;

template struct class_rape
    < cvt_fb_reading_t, &cvt_filebuf::_M_reading, cvt_filebuf_reading >;
template struct class_rape
    < cvt_wfb_reading_t, &cvt_wfilebuf::_M_reading, cvt_wfilebuf_reading >;

}

顺便说一下,这是上下文:http://pastie.org/1188625 .

更新

我在下面的答案中解决了重复问题。因此,现在我对一种确定性的、定义明确的解决方案感兴趣,该解决方案不涉及编辑任何目标代码,并允许同时破解模板的多个特化。 (给定的 hack 需要为每个目标模板专门化一个新的实例化。)

最佳答案

非法访问:

class ClassIWantToViolate
{
    // Internal State
    public:
        template<typename T> void violate() {} // Do nothing
};

然后在您的代码中您可以像这样违反该类:

namespace { struct Attack {}; }

template<>
void ClassIWantToViolate::violate<Attack>()
{
     // Access to internal state here.

     // This is your own version of violate based on a local specialization
     // Thus it is unique but still has access to internal state of the class.
}

关于c++ - 击败 C++ 访问资格的最干净方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3821107/

相关文章:

c++ - 如何在C/C++中删除当前用户的文件?

c++ - 使用共享库时内存仍然可达

c++ - 在邮件通知区域而不是收件箱中显示 Outlook 图标

c++ - 使用辅助方法操作字符串的范围问题

c# - 在不同的程序集中访问私有(private)方法 C#

c++ - 如何对小数位进行分组?

c++ - 添加到私有(private)变量不起作用

JavaScript,在不使用 eval 的情况下将私有(private)函数作为公共(public)方法中的字符串调用(显示模式)

facebook - 在 Facebook 上分享来自 "private"站点的内容时出现问题

c++ - 有 friend 看基类吗?