473,786 Members | 2,672 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
30 1925
On Sun, 18 Mar 2007 22:37:29 +0100 in comp.lang.c++, Filimon Roukoutakis
<fi*****@phys.u oa.grwrote,
>context in the program while it is by itself updated by f. Could you
comment on the invalidity of modifiable reference?
Doh! I was confusing the element access front() and back() with the
iterator functions begin() etc. Disregard all.

Mar 18 '07 #11
"Filimon Roukoutakis" <fi*****@phys.u oa.grwrote in message
news:et******** **@cernne03.cer n.ch...
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,
By your replies to the other posts, I take it you meant

void g() {
vec push_back( new Object );
f( vec[size() - 1] );
}

f( *(vec.end() - 1) );
may also work.

Your question seems to be, g made a new object, can f access that object?
The answer is yes. It would be the same if you did something like:

Object* MyObject = NULL;

f( Object*& obj )
{
// ...
}

Object* g
{
return new Object;
}

int main()
{
MyObject = g();
f( MyObject );
delete( MyObject );
}

You just happen to be storing it in a vector instead of (in thsi case) a
global variable. Once an object is allocated using new all you need is the
pointer to that memory to access the instance, until delete is called on it.
However you happen to get that pointer (global, from a vecotr, a paramter,
whatever).

Incidently, now a days "heap" is commonly called the "free store". I'm not
sure what the standard calls it.

Just make sure you delete the pointer when done.
Mar 18 '07 #12
Jim Langston wrote:
"Filimon Roukoutakis" <fi*****@phys.u oa.grwrote in message
news:et******** **@cernne03.cer n.ch...
>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,

By your replies to the other posts, I take it you meant

void g() {
vec push_back( new Object );
f( vec[size() - 1] );
}

f( *(vec.end() - 1) );
may also work.

Your question seems to be, g made a new object, can f access that object?
The answer is yes. It would be the same if you did something like:

Object* MyObject = NULL;

f( Object*& obj )
{
// ...
}

Object* g
{
return new Object;
}

int main()
{
MyObject = g();
f( MyObject );
delete( MyObject );
}

You just happen to be storing it in a vector instead of (in thsi case) a
global variable. Once an object is allocated using new all you need is the
pointer to that memory to access the instance, until delete is called on it.
However you happen to get that pointer (global, from a vecotr, a paramter,
whatever).

Incidently, now a days "heap" is commonly called the "free store". I'm not
sure what the standard calls it.

Just make sure you delete the pointer when done.

My problem is that when I try to delete the pointer inside f I get a
segmentation violation, so I figured that maybe new Object inside g is
stored as a const reference in the vector which cannot be modified
somehow and this produces the problem.
Mar 19 '07 #13
On Mon, 19 Mar 2007 10:28:48 +0100 in comp.lang.c++, Filimon Roukoutakis
<fi*****@phys.u oa.grwrote,
>
My problem is that when I try to delete the pointer inside f I get a
segmentation violation, so I figured that maybe new Object inside g is
stored as a const reference in the vector which cannot be modified
somehow and this produces the problem.
No. The contents of the vector, in this case the pointers, are fully
modifiable just as you thought. Even if that were not the case, const
pointers can be deleted as long as they came from 'new' to begin with.
I apologize for muddying the waters.

seg violation on deleting usually means either you are trying to delete
the same object twice, or some pointer that was never new'ed, or that
some random memory write elsewhere in the program has corrupted the
heap. Or something along those lines. Can be tricky to track down.

Mar 20 '07 #14
"Filimon Roukoutakis" <fi*****@phys.u oa.grwrote in message
news:et******** **@cernne03.cer n.ch...
: 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,

That part is ok. The only problem I see in the above code is
something that hasn't been mentioned yet:
vec.push_back(n ew Object);
This is not exception-safe: if push_back fails (because it
is unable to allocate a larger block of memory), the newly
allocated object will be leaked.

But this of course will be unrelated to the problem
you described later.
For that, be careful that you do not modify the vector
(e.g. by adding another element) as long as you are
using the reference returned by back().

hth -Ivan

--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form

Mar 20 '07 #15
On Tue, 20 Mar 2007 07:27:17 +0100, "Ivan Vecerina" wrote:
>The only problem I see in the above code is
something that hasn't been mentioned yet:
vec.push_back(n ew Object);
This is not exception-safe: if push_back fails (because it
is unable to allocate a larger block of memory), the newly
allocated object will be leaked.
Out-of-memory in C++ is usually handled by the new_handler, not with
exception handling. If one really needs to handle OOM with exception
handling vector::reserve () may be called in advance.

Best regards,
Roland Pibinger
Mar 20 '07 #16
"Roland Pibinger" <rp*****@yahoo. comwrote in message
news:45******** ******@news.uta net.at...
: On Tue, 20 Mar 2007 07:27:17 +0100, "Ivan Vecerina" wrote:
: >The only problem I see in the above code is
: >something that hasn't been mentioned yet:
: vec.push_back(n ew Object);
: >This is not exception-safe: if push_back fails (because it
: >is unable to allocate a larger block of memory), the newly
: >allocated object will be leaked.
:
: Out-of-memory in C++ is usually handled by the new_handler, not with
: exception handling.

What is your definition of "usually" ???
http://www.google.com/codesearch?q=set_new_handler
This gives 2-3'000 hits, many of them being declarations
in library headers. Not quite was I would call "usual".
Plus new_handler is required to either throw an exception,
or terminate the program. Does it really help here ?

: If one really needs to handle OOM with exception
: handling vector::reserve () may be called in advance.

Yes, this is one of several ways to address the problem.
All I am saying is that this issue is worth attention.

Regards,
Ivan

--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Brainbench MVP for C++ <http://www.brainbench.com

Mar 22 '07 #17
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,

filimon
Problem solved. The problem was that the above code produced a
segmentation violation in another part of the program. The fix was to
replace std::vector<Obj ect*with std::vector<Obj ect**and
vec.push_back(n ew Object*). Probably this was not obvious in the context
of the code snippet that was presented here. Thanks for the answers.

filimon
Mar 23 '07 #18
"Filimon Roukoutakis" <fi*****@phys.u oa.grwrote in message
news:eu******** **@cernne03.cer n.ch...
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,

filimon

Problem solved. The problem was that the above code produced a
segmentation violation in another part of the program. The fix was to
replace std::vector<Obj ect*with std::vector<Obj ect**and
vec.push_back(n ew Object*). Probably this was not obvious in the context
of the code snippet that was presented here. Thanks for the answers.
std::vector<som eclass*is usually bad design unless you are working with
polymorphism. Even then some would say use a smart pointer (although I use
naked pointers myself).

std::vector<som eclass**I could only think is bad design. You may want to
relook at what you are doing and see if this is absolutly necessary, it
sounds like a maintainance nightmare.
Mar 24 '07 #19
Filimon Roukoutakis wrote:
:: 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,
:::
::: filimon
::
:: Problem solved. The problem was that the above code produced a
:: segmentation violation in another part of the program. The fix was to
:: replace std::vector<Obj ect*with std::vector<Obj ect**and
:: vec.push_back(n ew Object*).

Agreeing with Jim Langston's post, I can only say that dynamically
allocating a single pointer is EXTREMELY unusual.

In my opinion, it is HIGHLY LIKELY that you have not actually solved the
problem, but only happen to hide it.
Bo Persson
Mar 24 '07 #20

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
8103
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
1792
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
4272
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
9650
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
10164
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
10110
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,...
1
7515
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
6748
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
5534
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4067
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
3670
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2894
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.