Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C++ > Dereferencing this in constructors initialiser list

Reply
Thread Tools

Dereferencing this in constructors initialiser list

 
 
Martin Zimmermann
Guest
Posts: n/a
 
      04-14-2004
Hi.

Is it allowed to dereference 'this' in a constructors initialiser list
to initialize a reference? (for later use)

Is this code legal or illegal?

class Foo;

class Bar
{
public:
Bar(Foo& foo)
: foo_(foo)
{
}
private:
Foo& foo_;
};

class Foo
{
public:
Foo()
: bar_(*this)
{
}
private:
Bar bar_;
};

int main()
{
}

Bye.
 
Reply With Quote
 
 
 
 
tom_usenet
Guest
Posts: n/a
 
      04-14-2004
On Wed, 14 Apr 2004 12:02:13 +0200, Martin Zimmermann
<(E-Mail Removed)> wrote:

>Hi.
>
>Is it allowed to dereference 'this' in a constructors initialiser list
>to initialize a reference? (for later use)


Yes. You can even do that before the constructor has even started. You
can only use that lvalue to access things that have already been
initialized (such as earlier base classes, earlier member variables
(in class declaration order)).

This is perfectly valid:

Foo* mem = static_cast<Foo*>(malloc(sizeof *mem));
assert(mem);
Foo& f = *mem;
//don't use f until it has been constructed!
new(mem) Foo();
//now you can use f safely.

Tom
--
C++ FAQ: http://www.parashift.com/c++-faq-lite/
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
 
Reply With Quote
 
 
 
 
Rob Williscroft
Guest
Posts: n/a
 
      04-14-2004
Martin Zimmermann wrote in news:c5j26s$369$02$(E-Mail Removed)-online.com in
comp.lang.c++:

> Hi.
>
> Is it allowed to dereference 'this' in a constructors initialiser list
> to initialize a reference? (for later use)
>
> Is this code legal or illegal?
>
> class Foo;
>
> class Bar
> {
> public:
> Bar(Foo& foo)
> : foo_(foo)
> {
> }
> private:
> Foo& foo_;
> };
>
> class Foo
> {
> public:
> Foo()
> : bar_(*this)
> {
> }
> private:
> Bar bar_;
> };
>
> int main()
> {
> }
>
> Bye.


Simple logic should suffice. In order to initialize the bar_
subobject 'this' must be dereferenced (this->bar_) anyway,
so yes you can.

Rob.
--
http://www.victim-prime.dsl.pipex.com/
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
initialiser list Fraser Ross C++ 1 12-24-2010 02:50 PM
array initialiser list, order of initialisation kwikius C++ 11 07-11-2008 08:06 PM
Copy constructors, de/constructors and reference counts Jeremy Smith C++ 2 08-02-2006 11:25 PM
Constructors that call other Constructors Dave Rudolf C++ 12 02-06-2004 03:26 PM
calling member functions from an initialiser list John Harrison C++ 2 06-25-2003 06:25 PM



Advertisments