Trying to push an element in to a vector

吃可爱长大的小学妹 提交于 2019-12-11 03:29:23

问题


In a header file (which I haven't written), a struct has been defined like this

struct MemoryMessage : public boost::counted_base { /*, public FastAlloc*/
  explicit MemoryMessage(MemoryMessageType aType)
   : theType(aType) {}
  explicit MemoryMessage(MemoryMessageType aType, MemoryAddress anAddress)
   : theType(aType) {}
  explicit MemoryMessage(MemoryMessageType aType, MemoryAddress anAddress, int anIdentifier)
   : theType(aType) {}
  explicit MemoryMessage(MemoryMessageType aType, MemoryAddress anAddress, VirtualMemoryAddress aPC)
   : theType(aType) {}
  explicit MemoryMessage(MemoryMessageType aType, MemoryAddress anAddress, VirtualMemoryAddress aPC, DataWord aData)
   : theType(aType) {}
  explicit MemoryMessage(MemoryMessage & aMsg)
   : theType(aMsg.theType) {} 
}

Later in my code, I have written

MemoryMessage testMsg;
class foo() {
  foo()
   : testMsg(MemoryMessage::test)
  {}
  std::vector< MemoryMessage > candidates;

  void bar() {
     candidates.push_back(testMsg);   
  }
}

But I get this error

error: no matching function for call to 'MemoryMessage::MemoryMessage(const MemoryMessage&)’
note: candidates are:MemoryMessage::MemoryMessage(MemoryMessage&)

What is wrong with that? I created a very small snippet. Please let me know if I missed something in my explanation.


回答1:


This line behind the scene invokes a copy constructor:

candidates.push_back(testMsg);   

The testMsg that push_back takes by const reference is placed into the vector by invoking a copy constructor inside std::vector's code. However, your constructor is declared explicit, so std::vector's code cannot access it.

Removing explicit designator from the copy constructor will fix this problem.



来源:https://stackoverflow.com/questions/24474684/trying-to-push-an-element-in-to-a-vector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!