473,811 Members | 3,220 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

when can pass by value be dangerous?

ceo
Hi there,

I'm reffering to a text that says following:

"To summarize: When a copy of an object is generated because it passed
to a function, the object's constructor function is not called.
However, when the copy of the object inside the function is destroyed,
its destructor is called.

By default, when a copy of an object is made, a bitwise copy occurs.
This means that the new object is an exact duplicate of the original.
The fact that an exact copy is made can, at time, be a source of
trouble. Even though objects are passed to functions by means of the
normal call-by-value parameter passing mechanism, which, in theory,
protects and insulates the calling argument. For example, if an object
used as an argument allocates memory and frees that memory when it is
destroyed, then its local copy inside the function will free the same
memory when its destructor is called. This will leave the original
object damaged and effectively useless."

Could someone give me an example that will damage the original object?

Thanks,
Ceo

Jul 23 '05 #1
9 1631
ceo wrote:
Hi there,
Could someone give me an example that will damage the original object?

Thanks,
Ceo


It's dangerous when the class you're passing is poorly written. E.g. a
primitive string class:

class stupid_string
{
char *data;
public:
stupid_string(c onst char *str) {
size_t l = strlen(str);
data = new char[l+1];
strcpy(data, str);
}
~stupid_string( ) {
delete[] data;
}

// Functions that actually make the class useful.
};

This class, when copied (as happens with pass-by-value), will not behave
correctly. Specifically, the new instance will refer to the same memory
with data. Thus, when the copy gets destructed, it will delete that memory
and the old instance refers to invalid memory.

The problem here is not pass-by-value, though. The problem is the lack of a
copy constructor.

stupid_string(c onst stupid_string &o) {
size_t l = strlen(o.data);
data = new char[l+1];
strcpy(data, o.data);
}

This way, the new instance has its own memory to mess with.
If it is not possible to give a class proper copy semantics, then you should
make it _impossible_ to copy it, by making the copy constructor and
assignment operator private and not giving them implementations :

class noncopyable
{
private:
noncopyable(con st noncopyable &o);
noncopyable &operator =(const noncopyable &o);
};

Another method is to derive from boost::noncopya ble, which accomplishes the
same thing, but in a way that makes it very clear what the code does.

class my_noncopyable : public boost::noncopya ble
{
};

http://www.boost.org/

--
Sebastian Redl
Jul 23 '05 #2

"ceo" <ce******@gmail .com> wrote in message
news:11******** **************@ f14g2000cwb.goo glegroups.com.. .
Hi there,

I'm reffering to a text that says following:

"To summarize: When a copy of an object is generated because it passed
to a function, the object's constructor function is not called.
However, when the copy of the object inside the function is destroyed,
its destructor is called.

By default, when a copy of an object is made, a bitwise copy occurs.
This means that the new object is an exact duplicate of the original.
The fact that an exact copy is made can, at time, be a source of
trouble. Even though objects are passed to functions by means of the
normal call-by-value parameter passing mechanism, which, in theory,
protects and insulates the calling argument. For example, if an object
used as an argument allocates memory and frees that memory when it is
destroyed, then its local copy inside the function will free the same
memory when its destructor is called. This will leave the original
object damaged and effectively useless."

Could someone give me an example that will damage the original object?

Thanks,
Ceo


Suppose the object has a pointer inside it to another, dynamically allocated
sub-object. What happens then? When the object is passed by value and gets
copied, its internal pointer simply gets copied. But now, both objects have
pointers to the SAME sub-object instead of to separate copies of that
sub-object.

This is exactly what the copy constructor is for! If your object contains
pointers to dynamic memory, then you're likely going to need a copy
constructor (as well as an assignment operator and a destructor), because
the default (compiler-generated) ones will not suffice. (Google for the
"Rule of Three".)

-Howard

Jul 23 '05 #3
ceo wrote:
...
I'm reffering to a text that says following:

"To summarize: When a copy of an object is generated because it passed
to a function, the object's constructor function is not called.
However, when the copy of the object inside the function is destroyed,
its destructor is called.
Out of context, the above makes no sense. This text must be referring to
some concrete class. Without the context, once again, it makes no sense.
By default, when a copy of an object is made, a bitwise copy occurs.
Same problem.
This means that the new object is an exact duplicate of the original.
The fact that an exact copy is made can, at time, be a source of
trouble. Even though objects are passed to functions by means of the
normal call-by-value parameter passing mechanism, which, in theory,
protects and insulates the calling argument. For example, if an object
used as an argument allocates memory and frees that memory when it is
destroyed, then its local copy inside the function will free the same
memory when its destructor is called. This will leave the original
object damaged and effectively useless."

Could someone give me an example that will damage the original object?
...


It seems to refer to the typical situation when a shallow copy is made
where a deep copy is really needed:

class A {
int* p;
public:
A() : p(new int[10]) {}
~A() { delete[] p; }
};

void foo(A x) {
/* Here 'x' is a shallow copy of the original 'a' in 'main', i.e.
'x.p' points to the same memory as 'a.p' */

...

/* The function is about to end. Destructor 'A::~A' will now
be called for object 'x'. The destructor will deallocate
memory pointed to by 'x.p' (and 'a.p') */
}

int main()
{
A a;
foo(a);
/* At this point object 'a' is broken. The destructor, called
at the end of 'foo', deallocated memory used to be pointed to
by 'a.p' */
}

--
Best regards,
Andrey Tarasevich

Jul 23 '05 #4
ceo wrote:
Hi there,

I'm reffering to a text that says following:

"To summarize: When a copy of an object is generated because it passed
to a function, the object's constructor function is not called.
That is nonsense. The copy constructor is called. And a constructor is not a
function, since it doesn't return anything (not even void). Note that for
each object of class type, a constructor and the destructor both are always
called exactly once.
However, when the copy of the object inside the function is destroyed,
its destructor is called.
That's right.
By default, when a copy of an object is made, a bitwise copy occurs.
This means that the new object is an exact duplicate of the original.
Again, nonsense. If it is of class type, the copy constructor gets called.
If no user-defined copy-constructor exists, a compiler-generated one will
do a member-wise copy, which again means that for each member of class
type, the copy constructor gets called. Only POD-types are copied bitwise.
The fact that an exact copy is made can, at time, be a source of
trouble. Even though objects are passed to functions by means of the
normal call-by-value parameter passing mechanism, which, in theory,
protects and insulates the calling argument. For example, if an object
used as an argument allocates memory and frees that memory when it is
destroyed, then its local copy inside the function will free the same
memory when its destructor is called. This will leave the original
object damaged and effectively useless."


If that happens, that class has a bug and needs fixing. It needs to adjusted
to satisfy the Rule of Three (tm), which says that if your class needs one
of a copy constructor, assignment operator or destructor, it almost
certainly needs all three of them.

PS: If that text is from a book, burn it! If it is in digital form, drill a
hole into the disk that contains it!

Jul 23 '05 #5
ceo wrote:

I'm reffering to a text that says following:

"To summarize: When a copy of an object is generated because it passed to a function, the object's constructor function is not called.
However, when the copy of the object inside the function is destroyed, its destructor is called.

By default, when a copy of an object is made, a bitwise copy occurs.
This means that the new object is an exact duplicate of the original.


I think you have been reading too much BullSchildt.

Jul 23 '05 #6
the destructor, is not fualty for accessing, shared, and static resources.

I'm not sure if he's full of SH___.
but create an object with a static variable to keep track of how many
objects are created.

pass one object into a function.
and when it returns, if he's right, then the static count will have a) Not
been incremented during the create, and b) decremented during the function
exit.
Droping the count to zero, when we know it is one.

This would certainly prove one way or the other. And just who is full of
SH__. and Who just doesn't Give a SH__.
:)

dan
"Old Wolf" <ol*****@inspir e.net.nz> wrote in message
news:11******** **************@ l41g2000cwc.goo glegroups.com.. .
ceo wrote:

I'm reffering to a text that says following:

"To summarize: When a copy of an object is generated because it

passed
to a function, the object's constructor function is not called.
However, when the copy of the object inside the function is

destroyed,
its destructor is called.

By default, when a copy of an object is made, a bitwise copy occurs.
This means that the new object is an exact duplicate of the original.


I think you have been reading too much BullSchildt.

Jul 23 '05 #7

DHOLLINGSWORTH2 wrote:
I'm not sure if he's full of SH___.
but create an object with a static variable to keep track of how many objects are created.

pass one object into a function.
and when it returns, if he's right, then the static count will have a) Not been incremented during the create, and b) decremented during the function exit.
Droping the count to zero, when we know it is one.
If you make sure that every constructor changes this variable, you're
right. However, how doy you force the compiler-generated default copy
ctor to change it? After all, the compiler-generated does nothing more
than copying each member. So, your count ends up counting the number
of calls to compiler-generated ctors.
This would certainly prove one way or the other. And just who is full of SH__. and Who just doesn't Give a SH__.


Actually, it will prove nothing if you don't understand
compiler-generated
constructors.

Regards,
Michiel Salters

Jul 23 '05 #8

"msalters" <Mi************ *@logicacmg.com > wrote in message
Actually, it will prove nothing if you don't understand
compiler-generated
constructors.


That was the mans point right?

He said, it does not call your constructor. But it does call your
destructor.

I dont need to know a thing about compiler-generated whosits to know when my
code has ran.

My method proves it right or wrong.

I will elaborate for you,

My method either Proves him to be correct, or my method will prove him to be
wrong. Either way My method proves it.

If he's wrong then there is no danger in passing emmediate, as described by
the man.
Jul 23 '05 #9
DHOLLINGSWORTH2 wrote:

"msalters" <Mi************ *@logicacmg.com > wrote in message
Actually, it will prove nothing if you don't understand
compiler-generated constructors.

That was the mans point right?


I don't think so.

He said, it does not call your constructor. But it does call your
destructor.
The quoted text said: "the object's constructor function is not called". But
that is clearly wrong. It is called. If you define a copy constructor, it
is called. If you don't, the compiler generates one that is called instead.
But whatever you do, the copy constructor is called.
I dont need to know a thing about compiler-generated whosits to know when
my code has ran.
Well, you do need to know that the compiler-generated one will not do what
you want, which means you have to know that you need to write your own one.
My method proves it right or wrong.

I will elaborate for you,

My method either Proves him to be correct, or my method will prove him to
be
wrong. Either way My method proves it.

If he's wrong then there is no danger in passing emmediate, as described
by the man.


Right. If you write the class correctly, it will prove him wrong.
Jul 23 '05 #10

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

Similar topics

10
3366
by: jeff regoord | last post by:
A user inputs a float value. The scanf() function gets the value. However, I need to create an error handler with an if else statement saying invalid input if the input is not a number. Does anybody know how I could do this?
1
2843
by: b83503104 | last post by:
When are they not consistent?
5
5774
by: rdemyan via AccessMonster.com | last post by:
I'm getting the following error message both when opening and closing my dB. The Microsoft Jet database engine cannot find the input table or query 'MSysAccessStorage'. Make sure it exists and that its name is spelled correctly. I'm using Access 2003 but the file format is Access 2000. -- Message posted via AccessMonster.com
89
6091
by: Cuthbert | last post by:
After compiling the source code with gcc v.4.1.1, I got a warning message: "/tmp/ccixzSIL.o: In function 'main';ex.c: (.text+0x9a): warning: the 'gets' function is dangerous and should not be used." Could anybody tell me why gets() function is dangerous?? Thank you very much. Cuthbert
9
2194
by: One | last post by:
I have a main.php file that calls a php navigation menu. I want to pass the menu file a parameter to tell it which menu to display. Inside the main.php I have : include "/home/ottadca1/public_html/includes/leftnav.php?menuid=dave"; But the error is : Warning:
8
4274
by: Gamma | last post by:
I'm trying to inherit subclass from System.Diagnostics.Process, but whenever I cast a "Process" object to it's subclass, I encounter an exception "System.InvalidCastException" ("Specified cast is not valid"). How do I fix it ? using System.Diagnostics; .. .. class NewProcess: Process {
94
30386
by: Samuel R. Neff | last post by:
When is it appropriate to use "volatile" keyword? The docs simply state: " The volatile modifier is usually used for a field that is accessed by multiple threads without using the lock Statement (C# Reference) statement to serialize access. " But when is it better to use "volatile" instead of "lock" ?
173
8207
by: Marty James | last post by:
Howdy, I was reflecting recently on malloc. Obviously, for tiny allocations like 20 bytes to strcpy a filename or something, there's no point putting in a check on the return value of malloc. OTOH, if you're allocating a gigabyte for a large array, this might fail, so you should definitely check for a NULL return.
8
2950
by: Yansky | last post by:
If I have the following function: function foo(){ alert('hi'); } and I don't need to pass any parameters to it, is calling it this way:
0
9605
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
10392
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10403
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
9208
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7671
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
6893
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();...
1
4341
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3868
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3020
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.