473,804 Members | 3,674 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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
32 2238
seank76 wrote:
On May 3, 4:28 pm, "Victor Bazarov" <v.Abaza...@com Acast.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.now rote:
* 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.now rote:
>* 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...@com Acast.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.now rote:
>* 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...@mari ani.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=tmplif e".
(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 objektorientier ter Datenverarbeitu ng
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.now rote:
* seank76:
On May 3, 2:51 pm, Gianni Mariani <gi3nos...@mari ani.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 objektorientier ter Datenverarbeitu ng
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.now rote:
* 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 objektorientier ter Datenverarbeitu ng
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...@inspir e.net.nzwrote:
On May 4, 9:33 am, seank76 <sean...@gmail. comwrote:
On May 3, 4:28 pm, "Victor Bazarov" <v.Abaza...@com Acast.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

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

Similar topics

3
4176
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 create a Reader object of the appropriate type for the file. Of course I can call close(), then pass the filename to the reader constructor and reopen the file there.
1
2594
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) {} private:
58
10188
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 code... TCHAR myArray; DoStuff(myArray);
3
3283
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(); Population pool = Population(& network); .... but this doesnt seem to work.. however the following works... Network * network = new Network();
11
1575
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); totgrossdlrval+=tf.enddlrval; i++; }
9
3346
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 limited c & c++ experience. Maybe some of you can help. the problem: I need several instances of a class whose (non-static!) methods should serve as callbacks for a dll (which can' be manipulated/adapted in any
8
2101
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
5785
by: Johannes Bauer | last post by:
Hello Group, please consider the following code #include <vector> #include <iostream> #define USE_CONST #define USE_STRING
1
1378
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 get data from class B into Class C. How should I go about this? I though I could make a function in class A that returns the data, but how do I get a pointer of Class A into Class B so I can access the data from class A Since Class B is created...
18
3275
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
9704
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9572
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10562
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10303
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10070
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7608
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6845
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5508
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3803
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.