Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
650 views
in Technique[技术] by (71.8m points)

c++ - Destructor is called when I push_back to the vector

I have this class definition:

class FlashStream
{
public:
    explicit FlashStream(const char * url, vector<uint8> * headers, vector<uint8> * data, void * ndata, void * notifyData = NULL, uint32 lastModified = NULL);
    ~FlashStream();
private:        
    NPStream      _stream;
    // ...
}

(NPStream description)

and its implemetation:

FlashStream::FlashStream(const char * url, vector<uint8> * headers, vector<uint8> * data, void * ndata, void * notifyData, uint32 lastModified)
{
    // ...
    memset(&_stream, 0, sizeof(NPStream));

    _stream.headers = new char[data->size()]; 

    memcpy((void*)_stream.headers, &(*data)[0], data->size());
    // ...
}

FlashStream::~FlashStream()
{
    // ...
    if(_stream.headers)
        delete [] _stream.headers;
    _stream.headers = NULL;
    // ...
}

Now, when I run this code:

// ...
vector<FlashStream> _streams;
// ...
_streams.push_back(FlashStream(url, headers, data, _npp.ndata, notifyData, lastModified));
// ...

Sometimes I have an error at delete [] _stream.headers; in the destructor of FlashStream, which is called when I push_back() to the vector<FlashStream> _streams.

I read this question on SO and a few another, but all the same don't know how to elegantly and efficiently fix the problem. May be the problem is in copy constructor, but I don't know how I can make it with memory allocation for NPStream.headers and NPStream.url?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This statement:

_streams.push_back(FlashStream(url, headers, data, _npp.ndata, notifyData, lastModified));

is equivalent to:

{
    FlashStream temp(url, headers, data, _npp.ndata, notifyData, lastModified);
    _streams.push_back(temp);
    // temp gets destroyed here
}

so, you create a temporary FlashStream object that is copied into the vector, then destructed afterwards. You can avoid this by using emplace_back() in C++11:

_streams.emplace_back(url, headers, data, _npp.ndata, notifyData, lastModified);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...