473,763 Members | 1,969 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

reference to a vector


I'm perusing source that quite frankly looks like a disaster in the
making. This is a case though where return by reference gets muddled
with my understand based on readings.

struct bar {
double variable;
void init() { memset ( this, 0, sizeof ( bar ) ); }
bar() { init(); }
bool operator <( bar & f ) const
{ return ( variable > f.variable ) ; }
};

std::vector< bar >& run_it ()
{
std::vector< bar > *ptr_f = new std::vector<bar >;
bar f;

f.variable = 99.;
ptr_f->push_back ( f );
return ( *ptr_f );
}

// later
int main()
{
std::vector<bar > f = run_it();
std::cout << f.size() << std::endl;
std::cout << f[ 0 ].variable << std::endl;

}
For starters, the memset seems to make an assumption that bar is a pod
type and it's not, but that aside my question is this:
The vector allocated in run_it is returned by reference to the local
variable f. I think though it's safe to state that the reference (i.e
temporary returned variable) has been reseated and copied to f. This
means the location of the allocated memory has been lost. If my
assessment is correct. I'm surpised the compiler (.NET) allowed me to
reseat ( right terminology ? ) the reference? Even more suprising is I
got the right answer ( 99 ).

I would think
const std::vector<bar >& f = run_it();
would be more prudent and it's now f's responsibility to clean up.

Thanks for the clarification..

Apr 28 '06 #1
10 2092
ma740988 wrote:
I'm perusing source that quite frankly looks like a disaster in the
making. This is a case though where return by reference gets muddled
with my understand based on readings.

struct bar {
double variable;
void init() { memset ( this, 0, sizeof ( bar ) ); }
bar() { init(); }
bool operator <( bar & f ) const
{ return ( variable > f.variable ) ; }
};

std::vector< bar >& run_it ()
{
std::vector< bar > *ptr_f = new std::vector<bar >;
bar f;

f.variable = 99.;
ptr_f->push_back ( f );
return ( *ptr_f );
}

// later
int main()
{
std::vector<bar > f = run_it();
std::cout << f.size() << std::endl;
std::cout << f[ 0 ].variable << std::endl;

}
For starters, the memset seems to make an assumption that bar is a pod
type and it's not,
Agreed. It's horrible, and quite possibly UB.

but that aside my question is this: The vector allocated in run_it is returned by reference to the local
variable f. I think though it's safe to state that the reference (i.e
temporary returned variable) has been reseated and copied to f.


No, ptr_f is a pointer to memory allocated from the free store. The
memory doesn't go away when run_it() exits, and run_it returns a
reference to the vector allocated on the free store. The problem is
that the memory leaks -- there's no way to delete the new'ed vector.
Apr 28 '06 #2
>> struct bar {
double variable;
void init() { memset ( this, 0, sizeof ( bar ) ); }
bar() { init(); }
bool operator <( bar & f ) const
{ return ( variable > f.variable ) ; }
};

std::vector< bar >& run_it ()
{
std::vector< bar > *ptr_f = new std::vector<bar >;
bar f;

f.variable = 99.;
ptr_f->push_back ( f );
return ( *ptr_f );
}

// later
int main()
{
std::vector<bar > f = run_it();
std::cout << f.size() << std::endl;
std::cout << f[ 0 ].variable << std::endl;

}
For starters, the memset seems to make an assumption that bar is a pod
type and it's not,

The memory layout is most likely the same as a double so memsetting it
has the same effect of memsetting a double.

Agreed. It's horrible, and quite possibly UB.
I don't see it that way. I think it is just a simple matter made
complicated but the behavior is still well defined (but platform dependent.)

The definition could have been trivially the following:

struct bar {
double variable;
bar():variable( 0.0){}
bool operator <( bar & f) const{
return variable > f.variable;
}
};
No, ptr_f is a pointer to memory allocated from the free store. The
memory doesn't go away when run_it() exits, and run_it returns a
reference to the vector allocated on the free store. The problem is
that the memory leaks -- there's no way to delete the new'ed vector.


I agree with you that the memory in OP's code is leaked. But it is
possible, though, to delete that memory. Simply

delete &f;

Regards,
Ben
Apr 29 '06 #3

"benben" <be******@yahoo .com.au> skrev i meddelandet
news:44******** *************** @news.optusnet. com.au...
struct bar {
double variable;
void init() { memset ( this, 0, sizeof ( bar ) ); }
bar() { init(); }
bool operator <( bar & f ) const
{ return ( variable > f.variable ) ; }
};

For starters, the memset seems to make an assumption that bar is a
pod
type and it's not,

The memory layout is most likely the same as a double so memsetting
it has the same effect of memsetting a double.


But you don't know for sure, because the struct is not a POD. The fact
that the struct has a constructor makes it a non-POD, and disqualifies
it from any use of memset on itself.

Agreed. It's horrible, and quite possibly UB.
I don't see it that way. I think it is just a simple matter made
complicated but the behavior is still well defined (but platform
dependent.)


The other problem is that the code assumes that double 0.0 has the
same bit pattern as char 0. This is not guaranteed either.

The definition could have been trivially the following:

struct bar {
double variable;
bar():variable( 0.0){}
bool operator <( bar & f) const{
return variable > f.variable;
}
};


Much better!
Bo Persson
Apr 29 '06 #4
benben wrote:

The memory layout is most likely the same as a double so memsetting it
has the same effect of memsetting a double.

If the memory layout is most likely the same as a double, then
memsetting it might have the same effect as memsetting a double.

Agreed. It's horrible, and quite possibly UB.

I don't see it that way. I think it is just a simple matter made
complicated but the behavior is still well defined (but platform
dependent.)


The behavior is undefined. That doesn't mean that it won't do what you
expect. It means that if you do that, you're outside the realm of the
C++ language definition. The danger is twofold: there's the slight
chance that all 0's for a floating-point type isn't 0.0, and there's the
greater change that the compiler puts some internal data in the object
that shouldn't be set to 0. So, in a nearly meaningless sense, it is,
indeed, platform dependent: what happens depends on your compiler. But
it's definitely not well defined.

The definition could have been trivially the following:
The definition SHOULD have been the following:

struct bar {
double variable;
bar():variable( 0.0){}
bool operator <( bar & f) const{
return variable > f.variable;
}
};


I'm all in favor of taking advantage of formally undefined behavior in
appropriate cases. In this case it isn't appropriate, because the
well-defined, portable form of initialization works just fine.
No, ptr_f is a pointer to memory allocated from the free store. The
memory doesn't go away when run_it() exits, and run_it returns a
reference to the vector allocated on the free store. The problem is
that the memory leaks -- there's no way to delete the new'ed vector.

I agree with you that the memory in OP's code is leaked. But it is
possible, though, to delete that memory. Simply

delete &f;


NO!!!!
std::vector<bar > f = run_it();


Sorry to shout, but f is a COPY of the object that the returned
reference referred to. It will be destroyed at the end of main. Deleting
it will blow things up horribly, because f was not allocated on the free
store.

--

Pete Becker
Roundhouse Consulting, Ltd.
Apr 29 '06 #5

Pete Becker wrote:
[...]
Sorry to shout, but f is a COPY of the object that the returned
reference referred to. It will be destroyed at the end of main. Deleting
it will blow things up horribly, because f was not allocated on the free
store.

Pete just so I understand this.
Put another way.
f _does_not_ get a copy but instead is an alias for the object that
the returned reference referred to. Correct?

Apr 29 '06 #6
> Sorry to shout, but f is a COPY of the object that the returned
reference referred to. It will be destroyed at the end of main. Deleting
it will blow things up horribly, because f was not allocated on the free
store.


Code in question:

std::vector< bar >& run_it ()
{
std::vector< bar > *ptr_f = new std::vector<bar >;
bar f;

f.variable = 99.;
ptr_f->push_back ( f );
return ( *ptr_f );
}

Please read carefully. Especially the *RETURN TYPE*.

Now tell me again if the vector ever gets copied.

Regards,
Ben
Apr 29 '06 #7
> Sorry to shout, but f is a COPY of the object that the returned
reference referred to. It will be destroyed at the end of main. Deleting
it will blow things up horribly, because f was not allocated on the free
store.


Oh ya I overlooked. Thanks for the correction!
Apr 29 '06 #8
> Pete just so I understand this.
Put another way.
f _does_not_ get a copy but instead is an alias for the object that
the returned reference referred to. Correct?


Pete was correct. f is copy constructed with a reference (alias)
returned from run_it().

My mistake in my previous post, sorry for that.

The code that allows deletion should be:

int main()
{
std::vector<bar >& f = run_it(); // Note its a reference now.
std::cout << f.size() << std::endl;
std::cout << f[ 0 ].variable << std::endl;
delete &f;
}

But a better way to do the same thing is to return a vector directly:

//std::vector< bar >& run_it ()
std::vector<bar > run_it()
{
std::vector<bar > v;
std::vector<bar > *ptr_f = &v;
bar f;

f.variable = 99.;
ptr_f->push_back ( f );
// return ( *ptr_f );
return v;
}

// later
int main()
{
std::vector<bar > f = run_it();
std::cout << f.size() << std::endl;
std::cout << f[ 0 ].variable << std::endl;

}
Apr 29 '06 #9
ma740988 wrote:
Pete Becker wrote:
[...]

Sorry to shout, but f is a COPY of the object that the returned
reference referred to. It will be destroyed at the end of main. Deleting
it will blow things up horribly, because f was not allocated on the free
store.


Pete just so I understand this.
Put another way.
f _does_not_ get a copy but instead is an alias for the object that
the returned reference referred to. Correct?


f is a copy of the object. Look at its definition. It's an object, not a
reference.

--

Pete Becker
Roundhouse Consulting, Ltd.
Apr 29 '06 #10

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

Similar topics

2
29522
by: tornado | last post by:
hi all, i am pretty new to c++. i have this problem for which i am unable to think a solution. i don't understand how to pass a vector refernce back to the callin function. And how this reference will be handled by the calling function ? Can any one in the group point me to the correct solution for it ? Any code snippets will be of great help. Thanks in advance.
9
11916
by: mjm | last post by:
Folks, Stroustrup indicates that returning by value can be faster than returning by reference but gives no details as to the size of the returned object up to which this holds. My question is up to which size m would you expect vector<double> returns_by_value() {
3
4145
by: klaas | last post by:
the following code gives rise to the beneath error message, only when a matrix object is instantiated as matrix<bool>, not with matrix<float>: /*returns a reference to the object at position (Row,Col) in matrix*/ template <class num_type,template <class T> class functor> num_type & matrix<num_type,functor >::operator()(const int Row,const int Col) {if (Row<rows && Col<cols) {vector<num_type> & x=matrix_core; //num_type & y=x;<-is also...
1
6350
by: terminator800tlgm | last post by:
I don't understand the difference between ojbect handle and reference. For example, class Stack { private: CD cd_obj; // cd object DVD & dvd_ref;// dvd reference Why is it that dvd_ref can ONLY be initialized in the Stack's
27
5972
by: Jason Heyes | last post by:
To my understanding, std::vector does not use reference counting to avoid the overhead of copying and initialisation. Where can I get a reference counted implementation of std::vector? Thanks.
41
8340
by: Berk Birand | last post by:
Hi, I am just learning about the array/pointer duality in C/C++. I couldn't help wondering, is there a way to pass an array by value? It seems like the only way to do is to pass it by reference?? Thanks, BB
4
4197
by: aaronfude | last post by:
Hi, Please consider the following class (it's not really my class, but it's a good example for my question): class Vector { int myN; double *myX; Vector(int n) : myN(n), myX(new double) { } double &operator()(int i) { return myX; }
12
1903
by: ypjofficial | last post by:
Hello All, I need to return a vector from a function.The vector is of int and it can contain as many as 1000 elements.Earlier I was doing //function definition vector<intretIntVector() { vector<intvecInt; /* //Populate the vector with int values.
8
4107
by: Chris Dams | last post by:
Dear all, The following is accepted by the compiler template <class Tclass test { public: typedef vector<int>::reference rt; }; but after the change int -T, obtaining the code fragment,
11
1922
by: Brian | last post by:
Dear Programmers, I have a class with a pointer to an array. In the destructor, I just freed this pointer. A problem happens if I define a reference to a vector of this kind of class. The destruction of the assigned memory seems to call the class destructor more than once. I don't know the reason or whether I used the vector class correctly. Attached is my program. Thanks for your help. Regards,
0
9566
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...
1
9943
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
9828
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
8825
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
7370
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
5271
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...
0
5410
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3529
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2797
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.