简体   繁体   中英

return a pointer to a member of an object that is created on the heap

So if I have a class

class Item {
 public:
  Item(int key, int value):key(key), value(value) {}
  int GetValue() {
    return value;
  }
 private:
  int key;
  int value;
}

If I create an Item object on the heap:

Item *item = new Item(1, 2);

Is it possible to get the pointer point to the value member of this object?

For example, I have another method from another class

int* GetValue(int k) {
  Item* item = ...;  // It finds the pointer to an Item object with key k that was created before.
  // Is there anyway I can return the pointer to the value member of this item?
 // Something like:
 return &(item->GetValue());  // This won't compile because item->GetValue() is a r-value. Is there any alternative way to walk around?
}

Try to add these line of code to your code.

template <class Tag, typename Tag::type Value>
struct Getter
{
    friend typename Tag::type get(Tag) {
        return Value;
    }
};

struct Tag_item {
    typedef int Item::*type;
    friend type get(Tag_item);
};

int* GetValue(int k) {
    static Item item(13, 14);
    // std::cout << item.GetValue() << std::endl; // This line to test output.
    return &(item.*get(Tag_item())); // If pItem is pointer then pItem->*get(Tag_item())
}
template struct Getter<Tag_item, &Item::value>;

See demo at http://coliru.stacked-crooked.com/a/3be5b80e848650c5

Credit to http://bloglitb.blogspot.com/2011/12/access-to-private-members-safer.html by Johannes Schaub - litb

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM