473,772 Members | 2,391 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Is this valid and moral C++?

Suppose that we have a function

f(Object*& obj)

and have declared a global std::vector<Obj ect*vec;

Is it valid to do

void g() {
vec.push_back(n ew Object);
f(vec.back());
}

ie does f() internally actually have read/write access to the Object
allocated in g() on the heap? If not, what would be the trick to achieve
this? Thanks,

filimon
Mar 18 '07 #1
30 1924
Filimon Roukoutakis wrote:
Suppose that we have a function

f(Object*& obj)

and have declared a global std::vector<Obj ect*vec;

Is it valid to do

void g() {
vec.push_back(n ew Object);
f(vec.back());
}

ie does f() internally actually have read/write access to the Object
allocated in g() on the heap? If not, what would be the trick to achieve
this? Thanks,
Yes, it is valid.

Objects allocated by new are available to any function before delete is
called on it.
Mar 18 '07 #2
On Sun, 18 Mar 2007 21:09:22 +0100 in comp.lang.c++, Filimon Roukoutakis
<fi*****@phys.u oa.grwrote,
>Suppose that we have a function

f(Object*& obj)

and have declared a global std::vector<Obj ect*vec;

Is it valid to do

void g() {
vec.push_back(n ew Object);
f(vec.back());
}
No. The function should receive the pointer argument by value. i.e.
f(Object* obj)

It is invalid to try to pass a modifiable reference to the result of
..back() , and while a const reference would work it has no particular
advantage.

Secondly, your global vector of Object* will NOT delete the objects
pointed to when it's destructor runs at the end of the program. There's
no big deal about reclaiming the memory at that point, but if Object's
destructor does anything else important you've got a problem.
>ie does f() internally actually have read/write access to the Object
allocated in g() on the heap?
Yes. In fact that is the only way of accessing the object that you have
left yourself at this point, which is fine.

Mar 18 '07 #3
David Harmon wrote:
On Sun, 18 Mar 2007 21:09:22 +0100 in comp.lang.c++, Filimon Roukoutakis
<fi*****@phys.u oa.grwrote,
>Suppose that we have a function

f(Object*& obj)

and have declared a global std::vector<Obj ect*vec;

Is it valid to do

void g() {
vec.push_back(n ew Object);
f(vec.back());
}

No. The function should receive the pointer argument by value. i.e.
f(Object* obj)

It is invalid to try to pass a modifiable reference to the result of
.back() , and while a const reference would work it has no particular
advantage.

Why is it "invalid" ?
Mar 18 '07 #4
David Harmon wrote:
On Sun, 18 Mar 2007 21:09:22 +0100 in comp.lang.c++, Filimon Roukoutakis
<fi*****@phys.u oa.grwrote,
>Suppose that we have a function

f(Object*& obj)

and have declared a global std::vector<Obj ect*vec;

Is it valid to do

void g() {
vec.push_back(n ew Object);
f(vec.back());
}

No. The function should receive the pointer argument by value. i.e.
f(Object* obj)

It is invalid to try to pass a modifiable reference to the result of
.back() , and while a const reference would work it has no particular
advantage.
I do want to pass a reference to the pointer so the pointer is
modifiable, or more precicely I want to use this pointer in another
context in the program while it is by itself updated by f. Could you
comment on the invalidity of modifiable reference?
>
Secondly, your global vector of Object* will NOT delete the objects
pointed to when it's destructor runs at the end of the program. There's
no big deal about reclaiming the memory at that point, but if Object's
destructor does anything else important you've got a problem.
>ie does f() internally actually have read/write access to the Object
allocated in g() on the heap?

Yes. In fact that is the only way of accessing the object that you have
left yourself at this point, which is fine.
ok for the above I knew, it was just a minimal example.

filimon
Mar 18 '07 #5
David Harmon wrote:
On Sun, 18 Mar 2007 21:09:22 +0100 in comp.lang.c++, Filimon Roukoutakis
<fi*****@phys.u oa.grwrote,
>>Suppose that we have a function

f(Object*& obj)

and have declared a global std::vector<Obj ect*vec;

Is it valid to do

void g() {
vec.push_back(n ew Object);
f(vec.back());
}

No. The function should receive the pointer argument by value. i.e.
f(Object* obj)
Why?
It is invalid to try to pass a modifiable reference to the result of
.back() , and while a const reference would work it has no particular
advantage.
The call f(vec.back()) does not pass anything "to the result of .back()".
What it does is: it initializes the Object*& parameter of f() with the
result of vec.back(), which so happens to be a reference (non-const in case
the non-const version of back() is called). There is nothing invalid about
it, as far as I can see.

E.g., f() could be:

f ( Object* & p_ref ) {
Object * dummy = new Object ();
std::swap( p_ref, dummy );
delete dummy;
}

Then f(vec.back()) would replace the last pointer with a new pointer whose
pointee has been default constructed.

Secondly, your global vector of Object* will NOT delete the objects
pointed to when it's destructor runs at the end of the program. There's
no big deal about reclaiming the memory at that point, but if Object's
destructor does anything else important you've got a problem.
Right: the vector will not do that by itself. So, the OP will have to take
care of deleting the pointers by himself.
[snip]

Mar 18 '07 #6
On Sun, 18 Mar 2007 22:37:29 +0100 in comp.lang.c++, Filimon Roukoutakis
<fi*****@phys.u oa.grwrote,
>I do want to pass a reference to the pointer so the pointer is
modifiable, or more precicely I want to use this pointer in another
context in the program while it is by itself updated by f. Could you
comment on the invalidity of modifiable reference?
What does it mean when your code attempts to modify via the reference,
giving in effect:
vec.back() = (some expression);

As I wrote to Gianni, It is forbidden by the standard to bind a
non-const reference to a temporary. This is one case where that rule
probably even makes sense. If you could actually change the value of
vec.back() without resizing the vector, it would break the vector. If
you think you can resize the vector by, for instance, incrementing
vec.back(), it doesn't work that way.

Mar 18 '07 #7
On Mon, 19 Mar 2007 08:30:34 +1100 in comp.lang.c++, Gianni Mariani
<gi*******@mari ani.wswrote,
>It is invalid to try to pass a modifiable reference to the result of
.back() , and while a const reference would work it has no particular
advantage.


Why is it "invalid" ?
It is forbidden by the standard to bind a non-const reference to a
temporary. This is one case where that rule probably even makes sense.
If you could actually change the value of vec.back() without resizing
the vector, it would break the vector. If you think you can resize the
vector by, for instance, incrementing vec.back(), it doesn't work that
way.

Mar 18 '07 #8
On Sun, 18 Mar 2007 18:13:46 -0400 in comp.lang.c++, Kai-Uwe Bux
<jk********@gmx .netwrote,
>The call f(vec.back()) does not pass anything "to the result of .back()".
What it does is: it initializes the Object*& parameter of f() with the
result of vec.back(), which so happens to be a reference (non-const in case
the non-const version of back() is called). There is nothing invalid about
it, as far as I can see.
Doh! I was confusing the element access front() and back() with the
iterator functions begin() etc. Disregard all.
Mar 18 '07 #9
On Mon, 19 Mar 2007 08:30:34 +1100 in comp.lang.c++, Gianni Mariani
<gi*******@mari ani.wswrote,
>It is invalid to try to pass a modifiable reference to the result of
.back() , and while a const reference would work it has no particular
advantage.


Why is it "invalid" ?

Doh! I was confusing the element access front() and back() with the
iterator functions begin() etc. Disregard all.
Mar 18 '07 #10

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

Similar topics

12
8209
by: lawrence | last post by:
I have a string which I want to send to eval(). How can I test it ahead of time to make sure it is valid code? I don't want to send it to eval and get parse errors. I want to do something like this: $valid = checkPHP($string); if ($valid) { eval($string); } else { $resultsObject->addToErrorResults("We wanted to send our template to eval(), but the PHP it contained was invalid.");
16
8102
by: siliconmike | last post by:
Hi, I'm looking for a reliable script that would connect to a host and somehow determine whether an email address is valid. since getmxrr() only gets the mx records.. Links/pointers ? Mike
1
1790
by: Anna | last post by:
Hi all. I have probably a rather stupid question. If there is an HTML document, XML-formed using JTidy, is there any tool to convert it to valid XHTML? I.e. so that all the tags and attribute values will be XHTML compliant. For example, if the original document has following snippet: <p><div>text</div></p> (which is not valid XHTML), the output would be something like <p><span>text</span></p> (which is valid XHTML). Thank you very much...
7
7292
by: JR | last post by:
Hey all, I have read part seven of the FAQ and searched for an answer but can not seem to find one. I am trying to do the all too common verify the data type with CIN. The code from the FAQ looks like this: #include <iostream>
23
1929
by: James Aguilar | last post by:
Someone showed me something today that I didn't understand. This doesn't seem like it should be valid C++. Specifically, I don't understand how the commas are accepted after the function 'fprintf'. What effect do they have in those parenthesis? I understand how the or is useful and why never to do it, I'm really just asking about that construction "(fprintf(stderr, "Can't open file.\n"), exit(0), 1))". ---- CODE ----
0
623
by: QA | last post by:
I am using a Business Scorecard Accelarator in a Sharepoint Portal 2003 using SQL Server 2005 I am getting the following error: Error,5/7/2005 10:50:14 AM,580,AUE1\Administrator,"Specified cast is not valid.","Microsoft.BusinessIntelligence.Scorecard.ScorecardException: Specified cast is not valid. ---> Microsoft.BusinessIntelligence.Scorecard.ScorecardException: Specified cast is not valid. ---> System.InvalidCastException: Specified...
10
4270
by: SpreadTooThin | last post by:
Hi I'm writing a python script that creates directories from user input. Sometimes the user inputs characters that aren't valid characters for a file or directory name. Here are the characters that I consider to be valid characters... valid = ':./,^0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ' if I have a string called fname I want to go through each character in
18
2962
by: John Salmon | last post by:
I was under the impression that the following was always valid: std::vector<Tv; .. T *p = &(v); But I was recently told that care was needed in case the vector was empty, i.e., when v.size() == 0. I'm hoping that the above expression is fine, even if v is empty, but
4
1250
by: George2 | last post by:
Hello everyone, In GotW #66, one of the moral is the exception handler of constructor should not do any like resource free task. I do not agree. Here is the quoated moral and my code to prove this moral will have memory leak. Anything wrong with my analysis? http://www.gotw.ca/gotw/066.htm
0
9619
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
10261
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...
0
10103
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...
0
9911
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...
0
8934
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...
0
6713
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
5354
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...
1
4007
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
3
2850
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.