获取 boost::any 变量的地址

Taking the address of a boost::any variable

考虑:

#include <boost/any.hpp>
#include <iostream>
#include <vector>
#include <string>

int main() {

    //Code snippet 1
    boost::any variable(std::string("Hello "));
    std::string* string_ptr_any = boost::any_cast<std::string>(&variable);
    std::cout << "Pointer value is " << string_ptr_any <<", variable's address is " << &variable << std::endl;
    //End Code snippet 1

    //Code snippet 2
    std::string normalstring = "hello_normal";
    std::string* normalstringptr = &normalstring;
    std::cout << "Pointer value is " << normalstringptr << ", variable's address is " << &normalstring << std::endl;
    //End Code snippet 2

    //Code snippet 3
    std::string& reference_of_string = boost::any_cast<std::string&>(variable);
    reference_of_string += "World!";
    std::cout << reference_of_string << std::endl;
    std::cout << boost::any_cast<std::string>(variable) << std::endl;
    //End Code snippet 3    

    getchar();

}

运行 compiler explorer 上的输出为:

Pointer value is 0xc2feb8, variable's address is 0x7ffec1620d68
Pointer value is 0x7ffec1620d40, variable's address is 0x7ffec1620d40
Hello World!
Hello World!

(Q1) 正如预期的那样,代码片段 2 为变量地址和指针提供了相同的值(在本例中为 0x7ffec1620d40)。但是,如何解释代码片段 1 中的相似代码导致两个不同的地址呢? (0xc2feb8 vs 0x7ffec1620d68) 这两个地址在内存中是什么关系?

(Q2) 我看不到用于转换 boost::any 变量的一致语法规则。代码片段1中,获取指针,语法为:

std::string* string_ptr_any = boost::any_cast<std::string>(&variable);

而在代码片段 3 中,要获取引用,语法为:

std::string& reference_of_string = boost::any_cast<std::string&>(variable);

更具体地说,为什么代码片段 1 中的语法不是:

std::string* string_ptr_any = boost::any_cast<std::string*>(&variable);

是否存在这些语法是一致的特殊情况的一般规则?

But what explains the similar code in Code snippet 1 giving rise to two different addresses? (0xc2feb8 vs 0x7ffec1620d68) What is the relationship between these two addresses in memory?

string_ptr_anystd::string对象的地址。 &variableboost::any 对象的地址。


why is not the syntax in Code snippet 1:

std::string* string_ptr_any = boost::any_cast<std::string*>(&variable);

因为 boost::any 不包含 std::string* 类型的对象。您只能转换为包含的类型或对它的引用。这将是编写片段 1 的另一种方法:

std::string* string_ptr_any = &boost::any_cast<std::string&>(variable);