473,395 Members | 1,442 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Passing a pointer of constructor

While going through my company's existing codebase, I saw a bunch of
weird lines.

Take a look at this one:

class A
{
public:
A(Foo *f) : _f(f) {}

private:
Foo *_f;
};

class B : public A
{
public:
B() : A(&(Foo &)Foo())) {}
};

How can you pass "Foo()" as the argument to the constructor of A ?
Wouldn't the memory that is allocated to Foo() get destroyed as soon
as we are out of the scope of B()?

What does this mean?

May 3 '07 #1
32 2186
Interesting...Are you sure this is compilable code?
g++ returns the following error :
error: invalid cast of an rvalue expression of type 'Foo' to type
'Foo&'
On May 3, 1:14 pm, seank76 <sean...@gmail.comwrote:
While going through my company's existing codebase, I saw a bunch of
weird lines.

Take a look at this one:

class A
{
public:
A(Foo *f) : _f(f) {}

private:
Foo *_f;

};

class B : public A
{
public:
B() : A(&(Foo &)Foo())) {}

};

How can you pass "Foo()" as the argument to the constructor of A ?
Wouldn't the memory that is allocated to Foo() get destroyed as soon
as we are out of the scope of B()?

What does this mean?

May 3 '07 #2
On May 3, 2:16 pm, pmouse <pmo...@cogeco.cawrote:
Interesting...Are you sure this is compilable code?
g++ returns the following error :
error: invalid cast of an rvalue expression of type 'Foo' to type
'Foo&'

On May 3, 1:14 pm, seank76 <sean...@gmail.comwrote:
While going through my company's existing codebase, I saw a bunch of
weird lines.
Take a look at this one:
class A
{
public:
A(Foo *f) : _f(f) {}
private:
Foo *_f;
};
class B : public A
{
public:
B() : A(&(Foo &)Foo())) {}
};
How can you pass "Foo()" as the argument to the constructor of A ?
Wouldn't the memory that is allocated to Foo() get destroyed as soon
as we are out of the scope of B()?
What does this mean?
I can definitely compile this using Sun forte 6.2 compiler.
Did you make sure to define class Foo correctly?
May 3 '07 #3
seank76 wrote:
While going through my company's existing codebase, I saw a bunch of
weird lines.

Take a look at this one:

class A
{
public:
A(Foo *f) : _f(f) {}

private:
Foo *_f;
};

class B : public A
{
public:
B() : A(&(Foo &)Foo())) {}
};

How can you pass "Foo()" as the argument to the constructor of A ?
Wouldn't the memory that is allocated to Foo() get destroyed as soon
as we are out of the scope of B()?

What does this mean?
It means you have problems.

The first thing that comes to mind is that &(Foo &)Foo()) might return
the address of a temporary. This means that A(Foo *f) : _f(f) {} is
being initialized to somthing that will be destroyed shortly after the
constructor for A returns.

All around, a very bad thing to be doing.
May 3 '07 #4
On May 3, 2:51 pm, Gianni Mariani <gi3nos...@mariani.wswrote:
seank76 wrote:
While going through my company's existing codebase, I saw a bunch of
weird lines.
Take a look at this one:
class A
{
public:
A(Foo *f) : _f(f) {}
private:
Foo *_f;
};
class B : public A
{
public:
B() : A(&(Foo &)Foo())) {}
};
How can you pass "Foo()" as the argument to the constructor of A ?
Wouldn't the memory that is allocated to Foo() get destroyed as soon
as we are out of the scope of B()?
What does this mean?

It means you have problems.

The first thing that comes to mind is that &(Foo &)Foo()) might return
the address of a temporary. This means that A(Foo *f) : _f(f) {} is
being initialized to somthing that will be destroyed shortly after the
constructor for A returns.

All around, a very bad thing to be doing.
That was my first response when I first saw this code.
However, a colleague of mine has claimed although it is "temporary",
the scope of it belongs to the class instance, NOT the constructor,
hence it is ok.
I don't know if this is right. (The code has been in production for
years so he must be right though...)
I will try to create a test program to validate.

In any case, I just wanted to know if this is a common programming
tactic by anybody.

May 3 '07 #5
seank76 wrote:
....
>
That was my first response when I first saw this code.
However, a colleague of mine has claimed although it is "temporary",
the scope of it belongs to the class instance, NOT the constructor,
hence it is ok.
That would be one weird compiler.

In standard C++ it is not, it's probably not even standard C++.
I don't know if this is right. (The code has been in production for
years so he must be right though...)
or lucky.
I will try to create a test program to validate.

In any case, I just wanted to know if this is a common programming
tactic by anybody.
I have never used it.
May 3 '07 #6
* seank76:
On May 3, 2:51 pm, Gianni Mariani <gi3nos...@mariani.wswrote:
>seank76 wrote:
>>While going through my company's existing codebase, I saw a bunch of
weird lines.
Take a look at this one:
class A
{
public:
A(Foo *f) : _f(f) {}
private:
Foo *_f;
};
class B : public A
{
public:
B() : A(&(Foo &)Foo())) {}
};

That was my first response when I first saw this code.
However, a colleague of mine has claimed although it is "temporary",
the scope of it belongs to the class instance, NOT the constructor,
hence it is ok.
Bullshit.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
May 3 '07 #7
On May 3, 4:09 pm, "Alf P. Steinbach" <a...@start.nowrote:
* seank76:
On May 3, 2:51 pm, Gianni Mariani <gi3nos...@mariani.wswrote:
seank76 wrote:
While going through my company's existing codebase, I saw a bunch of
weird lines.
Take a look at this one:
class A
{
public:
A(Foo *f) : _f(f) {}
private:
Foo *_f;
};
class B : public A
{
public:
B() : A(&(Foo &)Foo())) {}
};
That was my first response when I first saw this code.
However, a colleague of mine has claimed although it is "temporary",
the scope of it belongs to the class instance, NOT the constructor,
hence it is ok.

Bullshit.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Just compiled and ran a test program without any errors using Sun
forte and gcc1.2

the test program is the following:

#include <iostream>
#include <fstream>

using namespace std;

class A
{
public:
A() {}

void doThat() { cout << "HELLOSE SEAN!" << endl; }
};

class B
{
protected:
A* _a;

public:
B(A *a) : _a(a) {}

};

class C : B
{
public:
C() : B((A *)&(const A &)A()) {}

void dodo() { _a->doThat(); }
};

int main()
{
cout << "Starting test." << endl;

C c;

cout << "About the run C.dodo() " << endl;

c.dodo();
return 0;
}

May 3 '07 #8
seank76 wrote:
[..]
Just compiled and ran a test program without any errors using Sun
forte and gcc1.2

the test program is the following:

[..code involving undefined behaviour redacted..]
Go buy a lottery ticket, today is your lucky day.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
May 3 '07 #9
On May 3, 4:28 pm, "Victor Bazarov" <v.Abaza...@comAcast.netwrote:
seank76 wrote:
[..]
Just compiled and ran a test program without any errors using Sun
forte and gcc1.2
the test program is the following:
[..code involving undefined behaviour redacted..]

Go buy a lottery ticket, today is your lucky day.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask

Wow.

I didn't know there were so many highschool kids in this forum.
Real professionals know they see all kinds of weird **it in the
previous programmers' codes all the time.

But then... I guess this is not really the place to share weird
behaviors of a c++ compiler.

May 3 '07 #10
seank76 wrote:
On May 3, 4:28 pm, "Victor Bazarov" <v.Abaza...@comAcast.netwrote:
>seank76 wrote:
>>[..]
Just compiled and ran a test program without any errors using Sun
forte and gcc1.2
>>the test program is the following:
>>[..code involving undefined behaviour redacted..]

Go buy a lottery ticket, today is your lucky day.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask


Wow.

I didn't know there were so many highschool kids in this forum.
Finding yourself in familiar company?
Real professionals know they see all kinds of weird **it in the
previous programmers' codes all the time.
That's definitely true. They know. They see. Then they fix it or
throw it away.
But then... I guess this is not really the place to share weird
behaviors of a c++ compiler.
Do share, please, especially if it makes you feel better. None of
weird behaviours matter, but some schoolchildren find it entertaining.
My daughter always responds "I didn't fall!" when given advice not to
climb the furniture that can tip over easily. Well, she's not 4 yet.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
May 3 '07 #11
* seank76:
[quoting signatures]
Please don't quote signatures, please read the FAQ before posting.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
May 3 '07 #12
On May 3, 5:55 pm, "Alf P. Steinbach" <a...@start.nowrote:
* seank76:
[quoting signatures]

Please don't quote signatures, please read the FAQ before posting.
Please don't say Bullshit to a topic you don't understand.
Please read "Internet Etiquette" manual before you post.

May 3 '07 #13
* seank76:
On May 3, 5:55 pm, "Alf P. Steinbach" <a...@start.nowrote:
>* seank76:
>>[quoting signatures]
Please don't quote signatures, please read the FAQ before posting.

Please don't say Bullshit to a topic you don't understand.
Your colleague was bullshitting you.

Both Victor and I are old-timers in this group, both with extensive C++
experience (Victor more than I, I suspect), we're both contributors to
the FAQ, and we're both moderators of the moderated group.

You can generally trust us on technical things. Of course we don't
agree on everything. But those differences are over matters of
interpretation, style and so forth, not over trivial matters of fact.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
May 3 '07 #14
On May 4, 9:33 am, seank76 <sean...@gmail.comwrote:
On May 3, 4:28 pm, "Victor Bazarov" <v.Abaza...@comAcast.netwrote:
[..code involving undefined behaviour redacted..]
Go buy a lottery ticket, today is your lucky day.

Wow.
I didn't know there were so many highschool kids in this forum.
Real professionals know they see all kinds of weird **it in the
previous programmers' codes all the time.
I think you're missing the point. The code is dreadful and it
is exceptionally (un)lucky that it happens to work. The
object is destroyed as soon as the B constructor finishes.
If you don't fix it then you are the "**it programmer".

In fact the original code is not even well-formed; you fixed
that in your second example though.

Your example only appears to work because on your particular
compiler, it stores that function at a fixed address and that
function did not refer to any of the storage of the A object.
So the function gets through doing what it does, without running
into trouble due to there not actually being any object there.

I stress that this is NOT defined behaviour and is just a quirk
of your system. It might suddenly stop working at any moment.

May 3 '07 #15
seank76 wrote:
On May 3, 5:55 pm, "Alf P. Steinbach" <a...@start.nowrote:
>* seank76:
>>[quoting signatures]
Please don't quote signatures, please read the FAQ before posting.

Please don't say Bullshit to a topic you don't understand.
Please read "Internet Etiquette" manual before you post.
Sean, that's a technical term.

May 3 '07 #16
On May 3, 9:27 pm, seank76 <sean...@gmail.comwrote:
On May 3, 2:51 pm, Gianni Mariani <gi3nos...@mariani.wswrote:
seank76 wrote:
While going through my company's existing codebase, I saw a bunch of
weird lines.
Take a look at this one:
class A
{
public:
A(Foo *f) : _f(f) {}
private:
Foo *_f;
};
class B : public A
{
public:
B() : A(&(Foo &)Foo())) {}
};
How can you pass "Foo()" as the argument to the constructor of A ?
Wouldn't the memory that is allocated to Foo() get destroyed as soon
as we are out of the scope of B()?
What does this mean?
It means you have problems.
The first thing that comes to mind is that &(Foo &)Foo()) might return
the address of a temporary. This means that A(Foo *f) : _f(f) {} is
being initialized to somthing that will be destroyed shortly after the
constructor for A returns.
All around, a very bad thing to be doing.
That was my first response when I first saw this code.
However, a colleague of mine has claimed although it is "temporary",
the scope of it belongs to the class instance, NOT the constructor,
hence it is ok.
The collegue is wrong. There are two problems with this code:

-- It binds a temporary to a non-const reference (that is the
effect of the cast). This is illegal, and has been since
something like 1988 or 1989. Still, a lot of compilers
allow it by default. (Sun CC, for example, and I think
VC++, and probably some others.)

-- The lifetime of the temporary ends at the end of the
initialization expression---here, until we return from the
constructor of A. Until the mid-1990's, this was not well
specified, and different compilers behaved differently: g++
destroyed the temporary as soon as it was used (and casting
it counted as a use, so it wouldn't have lasted even into
the call to the constructor of A), CFront based compilers
destructed it at the end of the block (and I don't know when
in this case). Sun CC (which you mention elsewhere that you
use) was originally based on CFront, and even the most
recent versions of the compiler implement the extended
lifetime by default; if you want standard compliance, you
should be specifying something like "-features=tmplife".
(If I were you, I'd check out the -features option for the
version of the compiler you are using. The compiler is very
configurable, and like every other compiler I've used, the
defaults don't correspond to anything I'd want to use.)
I don't know if this is right. (The code has been in
production for years so he must be right though...)
Just because some code happens to work with a particular
compiler doesn't mean it's correct. Especially if that compiler
happens to be designed to support older, non-standard code by
default.
I will try to create a test program to validate.
In any case, I just wanted to know if this is a common programming
tactic by anybody.
I've never seen it before. It is, quite frankly, horrible, and
not conform with modern C++ (where modern means anything since
almost 20 years ago).

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

May 4 '07 #17
On May 3, 10:23 pm, seank76 <sean...@gmail.comwrote:
On May 3, 4:09 pm, "Alf P. Steinbach" <a...@start.nowrote:
* seank76:
On May 3, 2:51 pm, Gianni Mariani <gi3nos...@mariani.wswrote:
>seank76 wrote:
>>While going through my company's existing codebase, I saw a bunch of
>>weird lines.
>>Take a look at this one:
>>class A
>>{
>> public:
>> A(Foo *f) : _f(f) {}
>> private:
>> Foo *_f;
>>};
>>class B : public A
>>{
>> public:
>> B() : A(&(Foo &)Foo())) {}
>>};
That was my first response when I first saw this code.
However, a colleague of mine has claimed although it is "temporary",
the scope of it belongs to the class instance, NOT the constructor,
hence it is ok.
Bullshit.
Just compiled and ran a test program without any errors using Sun
forte and gcc1.2
Is that g++ 1.2? g++ is currently at 4.1.something, or more.
Any g++ before about 2.6 or 2.7 is totally worthless. Any g++
before 3.0 is hopelessly out of date.
the test program is the following:
#include <iostream>
#include <fstream>
using namespace std;
class A
{
public:
A() {}
void doThat() { cout << "HELLOSE SEAN!" << endl; }

};
class B
{
protected:
A* _a;
public:
B(A *a) : _a(a) {}
};
class C : B
{
public:
C() : B((A *)&(const A &)A()) {}
You added a const. That makes the code syntactically correct,
and means that the compiler is not required to issue a
diagnostic.
void dodo() { _a->doThat(); }
};
int main()
{
cout << "Starting test." << endl;
C c;
cout << "About the run C.dodo() " << endl;
c.dodo();
return 0;
}
The code contains undefined behavior, which means that it might
seem to work. Especially in simple cases. Try adding tracing
calls to the constructors (including the copy constructor, just
in case) and the destructor of A:

class A
{
public:
A() { std::cout << "A::ctor" << std::endl ; }
A( A const& ) { std::cout << "A::copy" << std::endl ; }
~A() { std::cout << "A::dtor" << std::endl ; }
// ...
} ;

With an up-to-date, conformant compiler, you should see the
message from the destructor before the message from A::doThat().

Another thing you might try is to add a member variable to A,
initialize it in the constructor, overwrite it in the
destructor, and output its value in A::doThat(); you should find
that it does not have the correct value. (The reason your code
seems to work, of course, is because you don't actually use
anything in A in doThat(). Just making doThat() virtual might
be enough to cause problems.)

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

May 4 '07 #18
On May 3, 11:58 pm, seank76 <sean...@gmail.comwrote:
On May 3, 5:55 pm, "Alf P. Steinbach" <a...@start.nowrote:
* seank76:
[quoting signatures]
Please don't quote signatures, please read the FAQ before posting.
Please don't say Bullshit to a topic you don't understand.
What your collegue claimed about the program was bullshit. It
shows simply that he doesn't really know C++.

You asked about particular code. We're telling you. It's not
legal. It never has been. And although it may work with some
older compilers, it would never pass code review in any well run
shop.

If it works, today, it is purely by chance, because you have a
compiler which is out of date, or because the undefined behavior
doesn't happen to reveal the error.
Please read "Internet Etiquette" manual before you post.
He did, I think. At least, it does say to not quote signatures.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

May 4 '07 #19
On May 3, 6:23 pm, Old Wolf <oldw...@inspire.net.nzwrote:
On May 4, 9:33 am, seank76 <sean...@gmail.comwrote:
On May 3, 4:28 pm, "Victor Bazarov" <v.Abaza...@comAcast.netwrote:
[..code involving undefined behaviour redacted..]
Go buy a lottery ticket, today is your lucky day.
Wow.
I didn't know there were so many highschool kids in this forum.
Real professionals know they see all kinds of weird **it in the
previous programmers' codes all the time.

I think you're missing the point. The code is dreadful and it
is exceptionally (un)lucky that it happens to work. The
object is destroyed as soon as the B constructor finishes.
If you don't fix it then you are the "**it programmer".

In fact the original code is not even well-formed; you fixed
that in your second example though.

Your example only appears to work because on your particular
compiler, it stores that function at a fixed address and that
function did not refer to any of the storage of the A object.
So the function gets through doing what it does, without running
into trouble due to there not actually being any object there.

I stress that this is NOT defined behaviour and is just a quirk
of your system. It might suddenly stop working at any moment.
Thanks for the answer.
This is what I was looking for, not some little kids telling me it's
bad code.
I am the one who is telling people around me it's bad code.
I just need to convince them why it's bad.

thanks for your help,
Sean.

May 4 '07 #20
On May 4, 4:56 am, James Kanze <james.ka...@gmail.comwrote:
On May 3, 10:23 pm, seank76 <sean...@gmail.comwrote:
On May 3, 4:09 pm, "Alf P. Steinbach" <a...@start.nowrote:
* seank76:
On May 3, 2:51 pm, Gianni Mariani <gi3nos...@mariani.wswrote:
seank76 wrote:
>While going through my company's existing codebase, I saw a bunchof
>weird lines.
>Take a look at this one:
>class A
>{
> public:
> A(Foo *f) : _f(f) {}
> private:
> Foo *_f;
>};
>class B : public A
>{
> public:
> B() : A(&(Foo &)Foo())) {}
>};
That was my first response when I first saw this code.
However, a colleague of mine has claimed although it is "temporary",
the scope of it belongs to the class instance, NOT the constructor,
hence it is ok.
Bullshit.
Just compiled and ran a test program without any errors using Sun
forte and gcc1.2

Is that g++ 1.2? g++ is currently at 4.1.something, or more.
Any g++ before about 2.6 or 2.7 is totally worthless. Any g++
before 3.0 is hopelessly out of date.
the test program is the following:
#include <iostream>
#include <fstream>
using namespace std;
class A
{
public:
A() {}
void doThat() { cout << "HELLOSE SEAN!" << endl; }
};
class B
{
protected:
A* _a;
public:
B(A *a) : _a(a) {}
};
class C : B
{
public:
C() : B((A *)&(const A &)A()) {}

You added a const. That makes the code syntactically correct,
and means that the compiler is not required to issue a
diagnostic.
void dodo() { _a->doThat(); }
};
int main()
{
cout << "Starting test." << endl;
C c;
cout << "About the run C.dodo() " << endl;
c.dodo();
return 0;
}

The code contains undefined behavior, which means that it might
seem to work. Especially in simple cases. Try adding tracing
calls to the constructors (including the copy constructor, just
in case) and the destructor of A:

class A
{
public:
A() { std::cout << "A::ctor" << std::endl ; }
A( A const& ) { std::cout << "A::copy" << std::endl ; }
~A() { std::cout << "A::dtor" << std::endl ; }
// ...
} ;

With an up-to-date, conformant compiler, you should see the
message from the destructor before the message from A::doThat().

Another thing you might try is to add a member variable to A,
initialize it in the constructor, overwrite it in the
destructor, and output its value in A::doThat(); you should find
that it does not have the correct value. (The reason your code
seems to work, of course, is because you don't actually use
anything in A in doThat(). Just making doThat() virtual might
be enough to cause problems.)

--
James Kanze (GABI Software) email:james.ka...@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Yeah... the problem with big companies is that the codebase is usually
10+ years old and compilers they use are horribly out-of-date.
I'm trying to change that by upgrading things here and there.
However, as you all probably know, the number one rule in business is,
don't fix it if it ain't broke.
So I need to show convincing reasonings before changing a line in the
code that's been in use for the last 7 or so years.

Now that I understand exactly what's going on, (thanks to James and
Olf Wolf) I will now attempt to fix the code.

thanks,
Sean.

May 4 '07 #21
On May 4, 5:04 am, James Kanze <james.ka...@gmail.comwrote:
On May 3, 11:58 pm, seank76 <sean...@gmail.comwrote:
On May 3, 5:55 pm, "Alf P. Steinbach" <a...@start.nowrote:
* seank76:
[quoting signatures]
Please don't quote signatures, please read the FAQ before posting.
Please don't say Bullshit to a topic you don't understand.

What your collegue claimed about the program was bullshit. It
shows simply that he doesn't really know C++.

You asked about particular code. We're telling you. It's not
legal. It never has been. And although it may work with some
older compilers, it would never pass code review in any well run
shop.

If it works, today, it is purely by chance, because you have a
compiler which is out of date, or because the undefined behavior
doesn't happen to reveal the error.
Please read "Internet Etiquette" manual before you post.

He did, I think. At least, it does say to not quote signatures.
I think either I was posting in a different language or some of you
don't read the postings carefully enough.
You guys make it seem as though I was arguing the code is legal and
you all should go to hell or something.

I thought the code looked weird and probably not right.
But I know it compiles and works right now. (whether it's C++ standard
or platform agnostic is irrelevant in a production environment unless
you are a software shop.)
So I was asking why and how it works.

Now, if you tell me "it's illegal" or "go buy a lottery ticket", I
just wasted my time posting to a newsgroup.
If you didn't understand what I was saying, or I really was talking
out of my ass, at least have the courtesy to just skip to the next
message.

Oh one more thing about what my "colleague" said.
As I know how computer programmers think, we tend to think nobody else
but me truly understands how to program since program is an art, not a
science. (...right?)
Therefore when somebody brings up a point that seems totally against
my belief, we tend to turn our heads and say "bullshit".
However, if you actually put in the time to think for a second instead
of typing away those 8 letters, you would have realized the
initialization block of the constructor is actually outside of the
bracketed scope and really belongs to the class instance scope
(basically the same scope as the definition of the constructor
itself).
Now, I didn't know C++ standard specifically limited the compilers to
destroy any temporaries after the initialization is done.
This might be true and sub-skilled programmers like myself come to a
forum like this one to seek such valuable knowledges.

If this was such a wide-known fact that a 4-year old should have
known, I sincerely apologies for my lack of intelligence.

thanks,
Sean

May 4 '07 #22
seank76 wrote:
[..]
So I was asking why and how it works.
"Works" is the wrong term. "Appears to work" is better.

And who the hell knows? The behaviour of the code is undefined
and there is nothing anybody can tell you except that it "works"
by pure luck. Going into speculations on how electrical signals
on the motherboard of your computer make it so happen that it
seems to "work" for you is not what we do here in comp.lang.c++.
That would really be a waste of time. Honestly. It has no merit.
Now, if you tell me "it's illegal" or "go buy a lottery ticket", I
just wasted my time posting to a newsgroup.
Yes, you did. Once somebody tells you "the behaviour of such and
such code is undefined", you can stop asking "why it works" right
there and then. Write that on a piece of paper and hang it on the
wall where it will catch your eye every so often.
If you didn't understand what I was saying, or I really was talking
out of my ass, at least have the courtesy to just skip to the next
message.
If your post would have been left alone, how would you then know
whether in fact you were talking nonsense or nobody simply cared
to read or understand what you were saying? At least here you've
got to the bottom of it (or so it seems).
[..]
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
May 4 '07 #23
On Fri, 04 May 2007 07:02:06 -0700, seank76 wrote:
On May 4, 5:04 am, James Kanze <james.ka...@gmail.comwrote:
>On May 3, 11:58 pm, seank76 <sean...@gmail.comwrote:
On May 3, 5:55 pm, "Alf P. Steinbach" <a...@start.nowrote:
[...]
I think either I was posting in a different language or some of you
don't read the postings carefully enough. You guys make it seem as
though I was arguing the code is legal and you all should go to hell or
something.
[more ranting snipped]

Hey, relax; you posted a reasonable question and got several, correct
answers (in a nutshell: your code has UB, your colleague was wrong) along
with detailed explanations, from people who know what they are talking
about; ok, some of the responses didn't mince words, but that's usenet
for you.

You got the best result you could hope for - be happy.

--
Lionel B
May 4 '07 #24
On May 4, 10:19 am, "Victor Bazarov" <v.Abaza...@comAcast.netwrote:
seank76 wrote:
[..]
So I was asking why and how it works.

"Works" is the wrong term. "Appears to work" is better.

And who the hell knows? The behaviour of the code is undefined
and there is nothing anybody can tell you except that it "works"
by pure luck. Going into speculations on how electrical signals
on the motherboard of your computer make it so happen that it
seems to "work" for you is not what we do here in comp.lang.c++.
That would really be a waste of time. Honestly. It has no merit.
Now, if you tell me "it's illegal" or "go buy a lottery ticket", I
just wasted my time posting to a newsgroup.

Yes, you did. Once somebody tells you "the behaviour of such and
such code is undefined", you can stop asking "why it works" right
there and then. Write that on a piece of paper and hang it on the
wall where it will catch your eye every so often.
If you didn't understand what I was saying, or I really was talking
out of my ass, at least have the courtesy to just skip to the next
message.

If your post would have been left alone, how would you then know
whether in fact you were talking nonsense or nobody simply cared
to read or understand what you were saying? At least here you've
got to the bottom of it (or so it seems).

Victor,

If you have told me that "the behavior of such and such code is
undefined since it violates such and such rule", there is no more
discussion as you have so correctly put it.

It so happens that wasn't the response I got from you or anyone at the
point of time. (In fact I'm not even sure if you or Alf gave me any
responses at all)
As you can see, when some people who know what they are talking about
replied with real answers, I was one happy camper.

So we should add it to the "FAQ" to only respond with real answers to
the questions.
I think this might be a bit more important that removing the
signature.

thanks,
Sean

May 4 '07 #25
seank76 wrote:
[..]
If you have told me that "the behavior of such and such code is
undefined since it violates such and such rule", there is no more
discussion as you have so correctly put it.
Yes, in _my_ response the "such and such rule" was missing. But in
his first post to this thread Gianni Mariani told you that you were
initialising something with an address of a temporary that was not
going to survive beyond the constructor's execution. Then you told
us that your colleague claimed that it's OK. Alf told you that it
was BS. It was. Your colleague was BSing you. Most likely from his
or her ignorance.
It so happens that wasn't the response I got from you or anyone at the
point of time. (In fact I'm not even sure if you or Alf gave me any
responses at all)
Too bad. You seem to have been too wrapped up in trying to defend
your colleague's point of view or getting offended by the flames you
received. <shrug Next time wear your flame-retardant shorts.
As you can see, when some people who know what they are talking about
replied with real answers, I was one happy camper.
<shrugNot everybody is in the business of making campers happy.
So we should add it to the "FAQ" to only respond with real answers to
the questions.
The FAQ is not the law, it cannot be enforced in an unmoderated NG.
If you need controlled environment, try 'comp.lang.c++.moderated'.
Here I, or anybody else, respond as they deem fit. Killfile me if
you don't like my responses. I won't feel it, don't you worry.
I think this might be a bit more important that removing the
signature.
It might.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
May 4 '07 #26
seank76 wrote:
....
>I stress that this is NOT defined behaviour and is just a quirk
of your system. It might suddenly stop working at any moment.

Thanks for the answer.
This is what I was looking for, not some little kids telling me it's
bad code.
I am the one who is telling people around me it's bad code.
I just need to convince them why it's bad.
Sean,

a) Everyone who has responded to you has been very courteous and
genuinely trying to help *you*.

b) If you don't understand why something is *bad code*, don't shoot the
messenger. Try to be a little introspective. (Who is the baby here?)

c) Usenet/emails are very often misread (as in the tone of the
document). Get beyond the perceived tone of usenet postings, in 99% of
cases, the tone you interpret is not the tone that was intended. In
other words, if someone seems to be extra nice, they're just as likely
extra annoyed.

d) You got your answer from 4 very experienced posters. I know they are
very experienced because I see their answers on this NG all the time and
the only errors I see they make are typos. Be happy.

e) Given the level of your question, this is not likely the only
question you're going to have. Annoying 4 of the regular posters with
assertions of being "children" is not likely to solicit any help next
time you need some.

Good luck.

Tell your boss I charge at $200/hr and you got 20 minutes of my time for
free. If he does not believe me that the code you have shown is a
problem, then I'd be more that willing to consult to confirm or deny.
Minimum 8hrs (not free).
May 4 '07 #27
On May 4, 11:51 am, seank76 <sean...@gmail.comwrote:
On May 4, 10:19 am, "Victor Bazarov" <v.Abaza...@comAcast.netwrote:
seank76 wrote:
[..]
So I was asking why and how it works.
"Works" is the wrong term. "Appears to work" is better.
And who the hell knows? The behaviour of the code is undefined
and there is nothing anybody can tell you except that it "works"
by pure luck. Going into speculations on how electrical signals
on the motherboard of your computer make it so happen that it
seems to "work" for you is not what we do here in comp.lang.c++.
That would really be a waste of time. Honestly. It has no merit.
Now, if you tell me "it's illegal" or "go buy a lottery ticket", I
just wasted my time posting to a newsgroup.
Yes, you did. Once somebody tells you "the behaviour of such and
such code is undefined", you can stop asking "why it works" right
there and then. Write that on a piece of paper and hang it on the
wall where it will catch your eye every so often.
If you didn't understand what I was saying, or I really was talking
out of my ass, at least have the courtesy to just skip to the next
message.
If your post would have been left alone, how would you then know
whether in fact you were talking nonsense or nobody simply cared
to read or understand what you were saying? At least here you've
got to the bottom of it (or so it seems).

Victor,

If you have told me that "the behavior of such and such code is
undefined since it violates such and such rule", there is no more
discussion as you have so correctly put it.

It so happens that wasn't the response I got from you or anyone at the
point of time. (In fact I'm not even sure if you or Alf gave me any
responses at all)
As you can see, when some people who know what they are talking about
replied with real answers, I was one happy camper.

So we should add it to the "FAQ" to only respond with real answers to
the questions.
I think this might be a bit more important that removing the
signature.

thanks,
Sean
I thought my reply in the first post tells u exactly what rule this
code violates, the g++ message is clear enough: you cannot cast a
rvalue returned by Foo() to Foo&

that is, the constructor Foo() returns a const reference type of Foo,
you simply cannot cast that to a lvalue and hope for the code to still
make sense - if your compiler compiles the code shown in your post,
then it needs to be thrown away.

Thing will be different, of course, if you are willing to use a "const
Foo&" instead. Modify A&B to look like:
class A
{
public:
A( const Foo* pf ) : _pF(pf) {}
const Foo* _pF;
};

class B : public A
{
public:
B() : A( &(const Foo&)Foo() ){}
};
will allow the code to compile.

What exactly is B() doing then?
Well, let's see, it creates a Foo object on the stack and get the
address of that object, then store it inside a constant pointer. I
think you and I both agree to this point. The question is then when
will the new Foo() object get destroyed? My bet it since it sits on
the stack, as soon as the function returns, it will get destroyed.
Your coworkers who wrote this code claims that the object has a
"scope" within the class, therefore it gets destroyed with the class -
I'm afraid that this claim makes no sense at all.

A simple test reveals what happens. Let's modify Foo to look like
this:
class Foo
{
public:
Foo() :a (0){ cout << "Foo()" << endl; }
~Foo() { cout << "~Foo()" << endl; }
Foo( const Foo& f ) : a(f.a) { cout << "copy Foo()" << endl; }
int a;
};

and let's declare a object of type B, then access the constant pointer
inside B to print out Foo::a:
B b;
cout << b._pF->a << endl;

Let's compile and run it:

peter@peter-laptop ~ $ g++ test.cpp -o test
peter@peter-laptop ~ $ ./test
Foo()
~Foo()
0

As demonstrated, The class's destructor is called before the access -
you are accessing memory that is not allocated, although the value did
print out correctly, that is only because no other object currently
uses that space yet. But this is now a potential bomb and will cost
your company a fortune to debug once it explodes.

What your coworker probably meant to do is:
B : A( new Foo() ) {}

and

~A () { if ( _pF ) delete _pF; }

if there exist a syntactically and logically correct answer, why not
stick to it?

Regards,

PQ

May 4 '07 #28
pmouse wrote:
On May 4, 11:51 am, seank76 <sean...@gmail.comwrote:
....
~A () { if ( _pF ) delete _pF; }
~A () { delete _pF; }

The if ( _pF ) is already checked by delete.
May 5 '07 #29
On May 4, 10:14 pm, Gianni Mariani <gi3nos...@mariani.wswrote:
pmouse wrote:
On May 4, 11:51 am, seank76 <sean...@gmail.comwrote:
...
~A () { if ( _pF ) delete _pF; }

~A () { delete _pF; }

The if ( _pF ) is already checked by delete.
Not in GCC/g++, and many other compilers that I use.
deleting a piece of memory twice will cause a double free exception
(run time)
On the other hand, free() does check for zero pointers.

Regards,

PQ

May 5 '07 #30
On May 5, 1:35 pm, pmouse <pmo...@cogeco.cawrote:
On May 4, 10:14 pm, Gianni Mariani <gi3nos...@mariani.wswrote:
pmouse wrote:
On May 4, 11:51 am, seank76 <sean...@gmail.comwrote:
...
~A () { if ( _pF ) delete _pF; }
~A () { delete _pF; }
The if ( _pF ) is already checked by delete.

Not in GCC/g++, and many other compilers that I use.
deleting a piece of memory twice will cause a double free exception
(run time)
On the other hand, free() does check for zero pointers.

Regards,

PQ
nevermind, I wasn't thinking.

Regards,

PQ

May 5 '07 #31
On May 5, 7:35 pm, pmouse <pmo...@cogeco.cawrote:
On May 4, 10:14 pm, Gianni Mariani <gi3nos...@mariani.wswrote:
pmouse wrote:
On May 4, 11:51 am, seank76 <sean...@gmail.comwrote:
...
~A () { if ( _pF ) delete _pF; }
~A () { delete _pF; }
The if ( _pF ) is already checked by delete.
Not in GCC/g++, and many other compilers that I use.
It is in every compiler I've ever used. Including g++.
deleting a piece of memory twice will cause a double free exception
(run time)
But there's nothing in your code above which has anything to do
with deleting an object twice. You're checking if the pointer
is null. (It would, of course, be better to do so explicitly,
rather than relying on implicit conversions.) And invoking
delete on a null pointer is legal, and works perfectly well with
all major compilers.

-
James Kanze (Gabi Software) email: ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

May 5 '07 #32
"seank76" <se*****@gmail.comwrote in message
news:11**********************@y5g2000hsa.googlegro ups.com...
On May 3, 5:55 pm, "Alf P. Steinbach" <a...@start.nowrote:
>* seank76:
[quoting signatures]

Please don't quote signatures, please read the FAQ before posting.

Please don't say Bullshit to a topic you don't understand.
Please read "Internet Etiquette" manual before you post.
Seank, please don't argue with Victor or Alf. They are the de facto C++
gurus in this newsgroup. They know more than everyone else combined. If
they say something is undefined, it is undefined.

Victor never said it was bullshit. He said to go buy a lottery ticket
because today is your lucky day. A tongue in cheek way of saying, you are
extremely lucky the code is working right now.

What your colliege told you, however, is bullshit as far as the C++ standard
is concerned, which is what we discuss in this newsgroup. If it happens to
work on your compiler in it's current version and OS doesn't mean it's not
undefined behavior. Undefined behavior is just that, undefined. Anything
can happen, including working as you want it to work. Just because it works
doesn't mean it's right.

The next version of your compiler the designers may decide to change
something internal that will break your code, as they have all the right to
do, since they only need to support well defined behavior.

Believe me, I have never seen Alf or Victor respond incorrectly to a topic
they didn't understand. It was just that I, or someone else, didn't
understand the topic ourselves. Victor was right, you are [un]lucky it
works. It is a crap shoot. Go ahead and buy yourself a lottery ticket.
May 5 '07 #33

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Sören | last post by:
Hi, I'd like advise on passing ownership of an iostream. The idea is that my factory class/function should open a file, read enough to detect file type (eg which soundfile format), then...
1
by: J Solowiej | last post by:
Hi, I am wondering: is it possible to pass pointer to member function (non static) to initialize another class? For exmaple: class X { public: typedef double (*F)(double); X(F f) : f_(f) {}...
58
by: jr | last post by:
Sorry for this very dumb question, but I've clearly got a long way to go! Can someone please help me pass an array into a function. Here's a starting point. void TheMainFunc() { // Body of...
3
by: John C | last post by:
Hi, I am a little uncertain about the concept of passing a reference to a class to another instance of a class. for instance I thought that the following was ok: Network network = Network();...
11
by: dave | last post by:
void CalcPortGrossRet(Funds tf,int fsize,PortFolio tp,int cmonth) { int i=0; float totgrossdlrval=0; char converter; while(i<fsize){ tf.enddlrval=(tf.dlrval*(tf.ret/100.0)+tf.dlrval);...
9
by: zholthran | last post by:
Hi folks, after reading several threads on this issue (-> subject) I fear that I got a problem that cannot easily be solved by the offered workarounds in an acceptable way, at least not with my...
8
by: Ivan Liu | last post by:
Hi, I'd like to ask if passing an object as an pointer into a function evokes the copy constructor. Ivan
7
by: Johannes Bauer | last post by:
Hello Group, please consider the following code #include <vector> #include <iostream> #define USE_CONST #define USE_STRING
1
by: stinger5900 | last post by:
First of all I am new to C++. I have created a class, lets say class A. When the constructor is called I create two new classes Class B and Class C, then are not the same class as A. I need to...
18
by: sanjay | last post by:
Hi, I have a doubt about passing values to a function accepting string. ====================================== #include <iostream> using namespace std; int main() {
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.