Hi all,

I am trying to use the class as a vector and pass parameters to the class. In loop.run(), I do certain things, then I would like to delete all the elements of the class.

1  class  SampleMarketDataClient
2  {
3       ....
4  };
5  int main()
6  {
7      vector<SampleMarketDataClient> clients;
8      while (!cin.eof())
9      {
10             if(cin.good())
11             {
12                    cin >> lineString;
13                     // Set up a market data subscription.
14                    clients.push_back( SampleMarketDataClient(lineString) );
15                    clients++;
16              }
17    }
18    loop.run();
19    clients.clear();
20 }

But this doesn't work. I think the line numbers 14, 15 & 19 are not the proper way to use the class as vectors. When I compile the program, I get errors. Is there a better way to do it? If so please let me know. Thanks a lot in advance.

Hi all,

I am trying to use the class as a vector and pass parameters to the class. In loop.run(), I do certain things, then I would like to delete all the elements of the class.

7      vector<SampleMarketDataClient> clients;
8      while (!cin.eof())
9      {
10             if(cin.good())
11             {
12                    cin >> lineString;
13                     // Set up a market data subscription.
14                    clients.push_back( SampleMarketDataClient(lineString) );
                 }
20 }

But this doesn't work. I think the line numbers 14, 15 & 19 are not the proper way to use the class as vectors. When I compile the program, I get errors. Is there a better way to do it? If so please let me know. Thanks a lot in advance.

That is not a valid way of initializing and passing an instance of type SampleMarketDataClient to vector clients....
Try this:

vector<SampleMarketDataClient> clients;
SampleMarketDataClient *temp;
 while (!cin.eof())
 {
     if(cin.good())
     {
           cin >> lineString;
           // Set up a market data subscription.
           temp = new SampleMArketDataClient(lineString);
           clients.push_back( *temp );
     }
 }

Good luck, LamaBot

Lazaro: you are causing huge memory leaks doing it that way. When are you going to delete those pointers? answer: never because they are overwritten with new values in each loop iteration. The parameter to your push_back is not saving the pointer but making a copy of the class just as in the OPs code. The pointer itself is discarded.

Lazaro: you are causing huge memory leaks doing it that way. When are you going to delete those pointers? answer: never because they are overwritten with new values in each loop iteration. The parameter to your push_back is not saving the pointer but making a copy of the class just as in the OPs code. The pointer itself is discarded.

They're not overwritten, this can be proved by the following:

#include <iostream>
#include <vector>

using namespace std;
 
class cool {
    public:
        cool(string hello) {str = hello;}
        ~cool(){};
        string str;
    protected:
    private:
};
int main()
{
    vector<cool> tempc;
    cool *temp;
    string hello[] = {"Yes", "No", "Maybe", "So"};
    int i;

    for (i=0;i<4;i++) {
        temp = new cool(hello[i]);
        tempc.push_back(*temp);
    }
    for (i=0;i<4;i++)
        cout << tempc[i].str << endl;
   ....
 return 0;
}

The above is essentially what I was doing in the OPs code. But you're right in that it'd be difficult and less intuitive to delete the pointers to the classes allocated on the heap the above method. So I modify it to this:

#include <iostream>
#include <vector>
using namespace std;
class cool {
    public:
        cool(string hello) {str = hello;}
        ~cool(){};
        string str;
    protected:
    private:
};
int main()
{
    vector<cool *> tempc;
    cool *temp;
    string hello[] = {"Yes", "No", "Maybe", "So"};
    int i;

    for (i=0;i<4;i++) {
        temp = new cool(hello[i]);
        tempc.push_back(temp);
    }
    for (i=0;i<4;i++)
        cout << tempc[i]->str << endl;
    for (i=0;i<4;i++)
        delete tempc[i];
 return 0;
}

Here is the OPs code modified:

vector<SampleMarketDataClient *> clients;  
SampleMarketDataClient *temp;
int i;
   
while (!cin.eof())     {
            if(cin.good())
            {
                   cin >> lineString;
                   // Set up a market data subscription.
                   temp = new SampleMarkDataClient(lineString);
                   clients.push_back(temp );
                 }
 }

Then to delete them, do the following:

for (i=0;i<clients.size();i++)
        delete clients[i];

Good luck, LamaBot

They're not overwritten, this can be proved by the following:

#include <iostream>
#include <vector>

using namespace std;
 
class cool {
    public:
        cool(string hello) {str = hello;}
        ~cool(){};
        string str;
    protected:
    private:
};
int main()
{
    vector<cool> tempc;
    cool *temp;
    string hello[] = {"Yes", "No", "Maybe", "So"};
    int i;

    for (i=0;i<4;i++) {
        temp = new cool(hello[i]);
        tempc.push_back(*temp);
    }
    for (i=0;i<4;i++)
        cout << tempc[i].str << endl;
   ....
 return 0;
}

new returns a pointer to the newly allocated memory in the heap storage. How do you propose on realeasing the allocated memory when you end up losing the addresses. Your code definately leaks memory as Mel says.

It can be proved by the following:

#include <iostream>
#include <vector>

using namespace std;

class cool
{
public:
    cool(string hello)
    {
        str = hello;
    }
    ~cool()
    {}
    ;
    string str;
};

int main()
{
    vector<cool> tempc;
    cool *temp;
    string hello[] =
        {"Yes", "No", "Maybe", "So"
        };
    int i;

    for (i=0;i<4;i++)
    {
        temp = new cool(hello[i]);
        cout << "Address returned: " << temp << endl ;
        tempc.push_back(*temp);
    }
    for (i=0;i<4;i++)
        cout << tempc[i].str << endl;

    getchar( ) ;
    return 0;
}

Yeah, now that I go back and read what he said a little more carefully, I realize I misinterpreted it. Sorry, my fault. Yes it does cause memory leaks, which is why I modified the code and posted it in my last posting. The address returned by "new", I differentiate and pass the first address of the instance on the heap. I thought, but thought wrong, that it'd work if you somehow obtained the address of each instance via Clients but that won't work. That is why I posted the modified code since what I essentially want to do is done with a vector of pointers.

Good luck OP, LamaBot

None of this will explain the OP's problem because he has not yet posted the errors he was getting -- the errors could be something completly unrelated. His original function should work because vectors do not require pointers -- we use vectors of c++ classes all the time, for example vector<string>. . One possible explaination for the OP's problem is that his class may not contain an explicit copy constructor. But that too is just guesswork since he did not post the declaration of the class.

We definitely need more information from the OP before we can suggest ways to correct his problem(s)

Hi all,

Thanks a lot for your reply. This is the error message I get.

asx_stock_price.cpp:14: error: no matching function for call to `
std::vector<SampleMarketDataClient*, std::allocator<SampleMarketDataClient*>
>::push_back(SampleMarketDataClient)'
/usr/include/g++/bits/stl_vector.h:596: error: candidates are: void
std::vector<_Tp, _Alloc>::push_back(const _Tp&) [with _Tp =
SampleMarketDataClient*, _Alloc = std::allocator<SampleMarketDataClient*>]

I hope this helps you

Hi

Sorry about that. I tried to change few things and now I dont get any error while compiling but when I run the program, I get 'Segmentation fault'.

vector<SampleMarketDataClient *> clients;
SampleMarketDataClient *temp;
while (!cin.eof())
{
      if(cin.good())
      {
    	// Read in the next line of text from the file
   	cin >> lineString;
	// Set up a market data subscription.
	temp = new SampleMarketDataClient(data, loop, lineString);
	clients.push_back( temp );
temp++;
      }
}

Anything you can suggest? Thanks a lot.

Hi

When I do this

1  class  SampleMarketDataClient2  {3       ....4  };5  int main()6  {7      vector<SampleMarketDataClient> clients;8      while (!cin.eof())9      {10             if(cin.good())11             {12                    cin >> lineString;13                     // Set up a market data subscription.14                    clients.push_back( SampleMarketDataClient(lineString) );15                    clients++;16              }17    }18    loop.run();19    clients.clear();20 }

Error Message is :

asx_stock_price.cpp:15: error: no `operator++(int)' declared for postfix `++',
trying prefix operator instead
asx_stock_price.cpp:15: error: no match for 'operator++' in '++clients'
/usr/include/g++/bits/ios_base.h: In copy constructor `std::basic_ios<char,
std::char_traits<char> >::basic_ios(const std::basic_ios<char,
std::char_traits<char> >&)':
/usr/include/g++/bits/stl_construct.h:78: instantiated from `void std::_Construct(_T1*, const _T2&) [with _T1 = SampleMarketDataClient, _T2 = SampleMarketDataClient]'
/usr/include/g++/bits/stl_vector.h:599: instantiated from `void std::vector<_Tp, _Alloc>::push_back(const _Tp&) [with _Tp = SampleMarketDataClient, _Alloc = std::allocator<SampleMarketDataClient>]'
asx_stock_price.cpp:14: instantiated from here
/usr/include/g++/bits/ios_base.h:668: error: `std::ios_base::ios_base(const
std::ios_base&)' is private
/usr/include/g++/bits/stl_construct.h:78: error: within this context
/usr/include/g++/streambuf: In copy constructor `std::basic_filebuf<char,
std::char_traits<char> >::basic_filebuf(const std::basic_filebuf<char,
std::char_traits<char> >&)':
/usr/include/g++/bits/stl_construct.h:78: instantiated from `void std::_Construct(_T1*, const _T2&) [with _T1 = SampleMarketDataClient, _T2 = SampleMarketDataClient]'
/usr/include/g++/bits/stl_vector.h:599: instantiated from `void std::vector<_Tp, _Alloc>::push_back(const _Tp&) [with _Tp = SampleMarketDataClient, _Alloc = std::allocator<SampleMarketDataClient>]'
asx_stock_price.cpp:14: instantiated from here
/usr/include/g++/streambuf:921: error: `std::basic_streambuf<_CharT,
_Traits>::basic_streambuf(const std::basic_streambuf<_CharT, _Traits>&)
[with _CharT = char, _Traits = std::char_traits<char>]' is private
/usr/include/g++/bits/stl_construct.h:78: error: within this context
/usr/include/g++/bits/stl_algobase.h: In member function `
phg::MarketDataClient& phg::MarketDataClient::operator=(const
phg::MarketDataClient&)':
/usr/include/g++/bits/stl_algobase.h:241: instantiated from `_OutputIter std::__copy(_RandomAccessIter, _RandomAccessIter, _OutputIter, std::random_access_iterator_tag) [with _RandomAccessIter = SampleMarketDataClient*, _OutputIter = SampleMarketDataClient*]'
/usr/include/g++/bits/stl_algobase.h:260: instantiated from `_OutputIter std::__copy_aux2(_InputIter, _InputIter, _OutputIter, __false_type) [with _InputIter = SampleMarketDataClient*, _OutputIter = SampleMarketDataClient*]'
/usr/include/g++/bits/stl_algobase.h:289: instantiated from `_OutputIter std::__copy_ni2(_InputIter, _InputIter, _OutputIter, __true_type) [with _InputIter = SampleMarketDataClient*, _OutputIter = __gnu_cxx::__normal_iterator<SampleMarketDataClient*, std::vector<SampleMarketDataClient, std::allocator<SampleMarketDataClient> > >]'
/usr/include/g++/bits/stl_algobase.h:314: instantiated from `_OutputIter std::__copy_ni1(_InputIter, _InputIter, _OutputIter, __true_type) [with _InputIter = __gnu_cxx::__normal_iterator<SampleMarketDataClient*, std::vector<SampleMarketDataClient, std::allocator<SampleMarketDataClient> > >, _OutputIter = __gnu_cxx::__normal_iterator<SampleMarketDataClient*, std::vector<SampleMarketDataClient, std::allocator<SampleMarketDataClient> > >]'
/usr/include/g++/bits/stl_algobase.h:349: instantiated from `_OutputIter std::copy(_InputIter, _InputIter, _OutputIter) [with _InputIter = __gnu_cxx::__normal_iterator<SampleMarketDataClient*, std::vector<SampleMarketDataClient, std::allocator<SampleMarketDataClient> > >, _OutputIter = __gnu_cxx::__normal_iterator<SampleMarketDataClient*, std::vector<SampleMarketDataClient, std::allocator<SampleMarketDataClient> > >]'
/usr/include/g++/bits/vector.tcc:118: instantiated from `__gnu_cxx::__normal_iterator<_Tp*, std::vector<_Tp, _Alloc> > std::vector<_Tp, _Alloc>::erase(__gnu_cxx::__normal_iterator<_Tp*, std::vector<_Tp, _Alloc> >, __gnu_cxx::__normal_iterator<_Tp*, std::vector<_Tp, _Alloc> >) [with _Tp = SampleMarketDataClient, _Alloc = std::allocator<SampleMarketDataClient>]'
/usr/include/g++/bits/stl_vector.h:759: instantiated from `void std::vector<_Tp, _Alloc>::clear() [with _Tp = SampleMarketDataClient, _Alloc = std::allocator<SampleMarketDataClient>]'
asx_stock_price.cpp:19: instantiated from here
/usr/include/g++/bits/ios_base.h:671: error: `std::ios_base&
std::ios_base::operator=(const std::ios_base&)' is private
/usr/include/g++/bits/stl_algobase.h:241: error: within this context
/usr/include/g++/streambuf: In member function `std::basic_filebuf<char,
std::char_traits<char> >& std::basic_filebuf<char, std::char_traits<char>
>::operator=(const std::basic_filebuf<char, std::char_traits<char> >&)':
/usr/include/g++/streambuf:924: error: `std::basic_streambuf<_CharT, _Traits>&
std::basic_streambuf<_CharT, _Traits>::operator=(const
std::basic_streambuf<_CharT, _Traits>&) [with _CharT = char, _Traits =
std::char_traits<char>]' is private
/usr/include/g++/bits/stl_algobase.h:241: error: within this context
../phg/constraints.h: At top level:
/usr/local/rfa6/Include/TIBMsg/TibMsg.h:11: warning: `char
SCCS_ID_TibMsg_hxx[56]' defined but not used
/usr/local/rfa6/Include/TIBMsg/TibErr.h:11: warning: `char
SCCS_ID_TibErr_hxx[56]' defined but not used
make[2]: *** [asx_stock_price.o] Error 1

Hi

Sorry about that. I tried to change few things and now I dont get any error while compiling but when I run the program, I get 'Segmentation fault'.

 vector<SampleMarketDataClient *> clients;
  SampleMarketDataClient *temp;
 while (!cin.eof())
 {
       if(cin.good())
       {
         // Read in the next line of text from the file
        cin >> lineString;
     // Set up a market data subscription.
     temp = new SampleMarketDataClient(data, loop, lineString);
     clients.push_back( temp );
 temp++;
       }
 }

Anything you can suggest? Thanks a lot.

Why do you have the line temp++? It doesn't seem like that would do what you want.

And if you wouldn't mind posting your compiler errors in code tags as well so they don't get butchered by the smilies... ;)

Edited 3 Years Ago by pyTony: fixed format

> Why do you have the line temp++? It doesn't seem like that would do what you want.
True, although it's unlikely to be causing syntax errors...

Don't know what happened in the OP's last post, but the code snippet was completely butchered, too...

Yeah, I kinda ignored the butchered post so I wasn't even looking at the syntax errors. But changing the memory pointed to by a pointer seems like a potential cause for a seg fault ;)

Hi

When I do this, I still get a segmentation fault. Any suggestions please

vector<SampleMarketDataClient *> clients;
SampleMarketDataClient *temp;
   while (!cin.eof())
      {
           if(cin.good())
           {
                // Read in the next line of text from the file
                cin >> lineString;
                // Set up a market data subscription.
               temp = new SampleMarketDataClient (data, loop, lineString);
               clients.push_back( temp );
            }
      }
     // And go!
     loop.run();
     for (int i=0;i<clients.size();i++)
                    delete clients[i];

Thanks

If you got a core dump use debugger to find out where the seg fault occurred. Its probably somewjhere else if your program. No body can tell unless you post the rest of your program.

When I do this


1 vector<SampleMarketDataClient *> clients;
2 while (!cin.eof())
3 {
4 if(cin.good())
5 {
6 // Read in the next line of text from the file
7 cin >> lineString;
8 // Set up a market data subscription.
9 clients.push_back( SampleMarketDataClient (data, loop, lineString) );
10 }
11}

I get a error message

asx_stock_price.cpp:9: error: no matching function for call to `
std::vector<SampleMarketDataClient*, std::allocator<SampleMarketDataClient*>
>::push_back(SampleMarketDataClient&)'
/usr/include/g++/bits/stl_vector.h:596: error: candidates are: void
std::vector<_Tp, _Alloc>::push_back(const _Tp&) [with _Tp =
SampleMarketDataClient*, _Alloc = std::allocator<SampleMarketDataClient*>]

Don't do it like this:

clients.push_back( SampleMarketDataClient (data, loop, lineString) );

Instead, use a separate object pointer to allocate your memory, and pass the memory address to the push_back function.

SampleMarketDataClient *objectPtr;
objectPtr = new SampleMarketDataClient(blah, blah);
clients.push_back(objectPtr);

[edit] Plus if you want to give us half a chance of finding the segmentation in your code, post all of it like Mel said!

Thanks a lot.

I got it working as you suggested and the segmentation fault was not because of this. I fixed it. Thanks once again.:)

Thanks a lot.

No problem, buddy. Glad to hear it's working.

I got it working as you suggested and the segmentation fault was not because of this.

I know it's tempting not to care, but don't forget to delete the memory once you're done with it, or else you get a memory leak.

This article has been dead for over six months. Start a new discussion instead.