开发者

Getting content carried by reference

开发者 https://www.devze.com 2023-03-09 03:50 出处:网络
I have a reference to a string object how can i get开发者_开发问答 the data from it. Here is my sample:

I have a reference to a string object how can i get开发者_开发问答 the data from it. Here is my sample:

string key = "key1";
gpointer somepointer;

GHashTable* myTable;
g_hash_table_insert(myTable,&key1,somepointer);         

GList *keysList = g_hash_table_get_keys(myTable);// here i got keys previously set
keysList = g_list_first(keysList);
string recentKey = (keysList->data);

data refers to reference of a string. How can i retrieve the data from the reference


If keysList->data is gpointer(void*), I guess some cast like the following is needed:

string recentKey = *(string*)keysList->data;

Hope this helps


If data is reference to a string then,

keysList->data returns the string.

#include<iostream>
#include <cstring>
#include <string>

using namespace std;

int main()
{
    string MyString("ABCD");
    string &MyString2 = MyString;
    char * cstr;

    cout<<"\n"<<MyString;
    cout<<"\n"<<MyString2;

    cstr = new char [MyString.size()+1];
    strcpy (cstr, MyString.c_str());

    cout<<"\n"<<cstr;
    delete[] cstr; 

    return 0;
}


What do you mean by "How can i retrieve the data from the reference?" Have you tried just doing it?

The only data in an std::string are the string length and the payload char* array.
keysList->data.length() will access the length while keysList->data.c_str() will access the char* array.

Your last statement is getting the data from the reference:

string recentKey = (keysList->data);

This statement creates a full copy of the string. Because it is a copy, any modifications to recentKey will not show up in keysList->data. Whether that is a good or bad thing depends on your intent.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号