Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
| Message-ID | <4lS4p.304$7P3.84@newsfe21.iad> (permalink) |
|---|---|
| Newsgroups | comp.std.c++ |
| From | Suncho <stupid@fake.email> |
| Subject | Re: this pointer question. Strange behaviour? |
| Organization | TeraNews.com |
| References | <56174c7a-2e04-4ae5-8471-4f957d19d353@p16g2000vbs.googlegroups.com> |
| Date | 2011-02-10 10:30 -0600 |
On 2/10/2011 8:24 AM, german diago wrote:
>
> Hello. I'm trying to use this pointer in a constructor to store an
> address of the this object in a global map like
> this:
>
> map<uintptr_t, void *> my_external_data;
>
>
> MyClass::MyClass() {
> auto object_address = reinterpret_cast<uintptr_t>(this);
> my_external_data.insert(make_pair(object_address, new ...));
> }
>
> PointerType * MyClass::getExternalPointer() {
> auto object_address = reinterpret_cast<uintptr_t>(this);
> return static_cast<PointerType
> *>(my_external_data[object_address]);
> }
>
> The problem is that when I print the this pointer in the constructor
> and in the getExternalPointer() functions,
> they don't point to the same address. Shouldn't the this pointer in
> the constructor be the same as in
> getExternalPointer? And if not, is there a workaround to achieve the
> same result? Thanks in advance.
>
I took your code and filled in the blanks. It worked fine for me using
MSVC10. The "this" pointers matched and when I indexed the map using
the address of the MyClass object, it returned the correct address of
the other object. Which compiler are you using?
#include <map>
#include <utility>
#include <iostream>
using std::map;
using std::make_pair;
using std::cout;
typedef int * PointerType;
map<uintptr_t, void *> my_external_data;
class MyClass {
public:
MyClass (void);
PointerType * getExternalPointer (void);
};
MyClass::MyClass() {
auto object_address = reinterpret_cast<uintptr_t>(this);
my_external_data.insert(make_pair(object_address, new int(5)));
cout << this << '\n';
}
PointerType * MyClass::getExternalPointer() {
auto object_address = reinterpret_cast<uintptr_t>(this);
cout << this << '\n';
return static_cast<PointerType *>(my_external_data[object_address]);
}
int main (int argc, char * argv[])
{
MyClass test_obj;
// They're the same.
cout << my_external_data[reinterpret_cast<uintptr_t>(&test_obj)]
<< '\n' << test_obj.getExternalPointer() << '\n';
return 0;
}
Output:
0024F963
0024F963
002C0990
002C0990
--
[ comp.std.c++ is moderated. To submit articles, try posting with your ]
[ newsreader. If that fails, use mailto:std-cpp-submit@vandevoorde.com ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html ]
Back to comp.std.c++ | Previous | Next — Previous in thread | Find similar
this pointer question. Strange behaviour? german diago <germandiago@gmail.com> - 2011-02-10 07:24 -0600 Re: this pointer question. Strange behaviour? Suncho <stupid@fake.email> - 2011-02-10 10:30 -0600
csiph-web