小编LTh*_*ode的帖子

如何清理(用随机字节覆盖)std :: string内部缓冲区?

考虑一个场景,std::string用于存储秘密.一旦它被消耗并且不再需要它,最好清理它,即覆盖包含它的内存,从而隐藏秘密.

std::string提供一个函数const char* data()返回指向(自C++ 11)连续内存的指针.

现在,由于内存是连续的,并且由于范围结束,变量将在清理后立即销毁,因此安全:

char* modifiable = const_cast<char*>(secretString.data());
OpenSSL_cleanse(modifiable, secretString.size());
Run Code Online (Sandbox Code Playgroud)

根据这里引用的标准:

$ 5.2.11/7 -注意:根据目的,通过指针,左值或指针以从得到的数据成员的写操作的类型const_cast即擅自抛弃一个const-qualifier68可能会产生不确定的行为(7.1.5.1).

否则会提出建议,但是上面的条件(连续的,待去除的)是否安全?

c++ stdstring c++11

25
推荐指数
4
解决办法
2009
查看次数

变量模板转换为std :: function <R(ARGS ...)>与GCC而不是MSVC2013一起使用,为什么?

如果这是重复,我会道歉.我在搜索中找不到任何东西.

我可以使用任何最新的功能c ++ 11/c ++ 14.如有必要,我可以升级到VS2015.

我正在尝试编写一个类,它将在分配时自动转换为具有特定签名的std :: function.我有与GCC一起使用的代码,但它在MSVC2013上失败了.代码是重新创建错误的代码段.WTF MSVC?!

另外我知道这是有风险的代码,自动转换函数指针等,但它是私有的插件库实现,我只想定义一次函数签名.

如果有另一种方法可以编写在main()中完成相同功能的代码并且同时适用于这两种方法,那么我就听见了.

GCC c ++ 11工作正常 - 演示

#include <functional>
#include <string>
#include <iostream>

class FunctionPointer
{
    void* fp;
public:
    FunctionPointer(void* ptr)
        : fp(ptr)
    {}

    // Overload casting operator to 
    // a certain function signiture
    template<class R, class... ARGS>
    operator std::function<R(ARGS...)>(){
        typedef R(*func_ptr)(ARGS...);
        return std::function<R(ARGS...)>((func_ptr)fp);
    }
};

void hello(std::string msg){
    std::cout << "Hello " << msg << std::endl;
}

int main() {

    FunctionPointer f((void*)hello);

    std::function<void(std::string)> func_hello = f;

    func_hello("World!");

    return …
Run Code Online (Sandbox Code Playgroud)

c++ variadic-templates c++11 c++14

22
推荐指数
1
解决办法
580
查看次数

如何在C++中为MPL向量的所有成员显式实例化模板?

请考虑以下头文件:

// Foo.h
class Foo {
    public: 
        template <typename T>
        void read(T& value);
};
Run Code Online (Sandbox Code Playgroud)

我想Foo::read在源文件中显式实例化成员函数模板,包括在boost::mpl::vector:

// Foo.cc
#include <boost/mpl/vector.hpp>
#include <boost/mpl/begin_end.hpp>
#include "Foo.h"

template <typename T>
void Foo::read(T& value) { /* do something */ }

typedef boost::mpl::vector<int, long, float> types;

// template Foo::read<int  >(int&);
// template Foo::read<long >(long&);
// template Foo::read<float>(float&);

// instantiate automatically ???
Run Code Online (Sandbox Code Playgroud)

可能吗?谢谢,丹尼尔.

编辑

我找到了一些解决方案 - 似乎Foo::read<T>在结构的构造函数中指定一个指针,然后声明该变量,导致实例化:

// intermezzo
template <typename T> struct Bar {
    Bar<T>() {
        void (Foo::*funPtr)(T&) = &Foo::read<T>; …
Run Code Online (Sandbox Code Playgroud)

c++ boost vector boost-mpl explicit-instantiation

20
推荐指数
1
解决办法
2066
查看次数