KKlouzal
KKlouzal

Reputation: 722

Deque emplace_back New Pointer To Object

I'm creating a new pointer to a new object and immediately push_front into a deque. I want to instead use emplace_front but am getting a compiler error.

My objects constructor requires 1 string argument.

std::deque<NetPacket*> q_IncomingPackets;

q_IncomingPackets.push_back(new NetPacket(std::string(uncompressed_data, retVal))));
q_IncomingPackets.emplace_back(std::string(uncompressed_data, retVal));

Following references from other websites I thought I could simply swap push_back for emplace_back but get the following error:

Error   C2440   'initializing': cannot convert from 'std::basic_string<char,std::char_traits<char>,std::allocator<char>>' to 'PeerNet::NetPacket *' PeerNet \vc\include\xmemory0    737

The references don't talk about using emplace when creating new pointers to objects, only concrete objects. cppreference.com cplusplus.com

Upvotes: 0

Views: 330

Answers (1)

Mine
Mine

Reputation: 4241

std::deque::emplace_back expects Args&&... args to construct value_type, which here is NetPacket*.

There is no way to construct NetPacket* from std::string, that's why the compiler error says.

Since your value type is NetPacket* (it's a raw pointer), there's no too much difference between push_back and emplace_back.

Upvotes: 1

Related Questions