CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 12 of 12

Threaded View

  1. #1
    Join Date
    Mar 2010
    Posts
    16

    Class pointer and vector problem

    As the title shows, I find it hard to come up for a good description of the problem I encountered.

    Please can some of you guru's help me?

    Code:
    #include <vector>
    
    class sD
    {
    private:
       float* _d;
    public:
        sD(){};
        ~sD(){ delete _d; }
       sD(const sD & D):_d(new float((*D._d))){}
       sD(float d){ _d = new float(d); }
       operator float(){ return *_d;
    };
    
    class tst{
    private:
       std::vector<sD> vec;
    public:
       tst(){};
       void insert(float sD){ vec.insert(vec.begin(), sD); }
       float operator[](std::vector<sD>::size_type i){ return vec[i]; }
    };
    
    int main(){
        tst t;
        t.insert(10);
        t.insert(20);
        float tmp1 = t[1];// tmp1 holds 10
        float tmp2 = t[0];// tmp2 holds ?
    }
    This is a distilled segment of the code. The actual code is much bigger.

    I would expect tmp2 to be 20.
    If I replace "vec.insert(vec.begin(), sD);" with "vec.push_back(sD);" than as expected; tmp2 holds 10 and tmp1 holds 20.

    Why doesn’t the tmp2 of my code hold 20? How can I remedy this behaviour?
    Last edited by po0ky; May 30th, 2011 at 09:29 AM.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured