问题
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