是否可以声明 boost::type_erasure::any
以从字符串文字或 char const*
构造和分配的方式自动将字符串复制到 std::string
并将其存储在 boost::type_erasure::任何
对象?
默认情况下,boost::type_erasure::any
只存储字符串指针。
目的是避免当我的 any
类型的用户分配一个字符串指针给它时,假设将进行复制(如 std::string
会),然后字符串的生命周期在我的 any
被读取之前结束,导致崩溃。
例子:
#include <boost/type_erasure/operators.hpp>
#include <boost/type_erasure/any.hpp>
#include <boost/type_erasure/any_cast.hpp>
#include <boost/type_erasure/relaxed.hpp>
#include <boost/mpl/vector.hpp>
#include <iostream>
namespace te = boost::type_erasure;
using my_any = te::any< boost::mpl::vector<
te::copy_constructible<>,
te::destructible<>,
te::typeid_<>,
te::relaxed
/* I believe some changes here would do the trick */
>>;
using namespace std;
int main()
{
// Store an std::string by explicitly calling string constructor.
my_any a = string("abc");
// The following should copy-construct an std::string too but it just stores
// the string pointer.
my_any b = "abc";
// Works as expected.
cout << te::any_cast<string>( a ) << endl;
// This crashes because the underlying type of b is not std::string.
// With some changes to the my_any type this shouldn't crash anymore.
cout << te::any_cast<string>( b ) << endl;
}
最佳答案
不,any
存储任何内容。 const char*
是任何东西。
请注意,"hello"s
是 std::string
类型的文字。
关于c++ - 从 C 字符串构造 boost::type_erasure::any 但存储为 std::string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42837888/