Below is minimal code to reproduce the error.
#include <iostream>
#include <mutex>
#include <vector>
class A {
std::mutex mutex;
public:
A(){};
};
int main()
{
std::vector<std::pair<std::string,A>> aa;
A a;
//aa.push_back(std::make_pair(std::string("aa"),A()));
//aa.push_back(std::make_pair(std::string("aa"),a));
aa.push_back(std::make_pair(std::string("aa"),std::move(a)));
}
Below is error.
Microsoft (R) C/C++ Optimizing Compiler Version 19.16.27026.1 for x64
Copyright (C) Microsoft Corporation. All rights reserved.
C:\Program Files (x86)\Microsoft Visual
Studio\2017\Community\VC\Tools\MSVC\14.16.27023\include\xlocale(319):
warning C4530: C++ exception handler used, but unwind semantics are
not enabled. Specify /EHsc C:\Program Files (x86)\Microsoft Visual
Studio\2017\Community\VC\Tools\MSVC\14.16.27023\include\utility(405):
error C2440: '<function-style-cast>': cannot convert from 'initializer
list' to '_Mypair' C:\Program Files (x86)\Microsoft Visual
Studio\2017\Community\VC\Tools\MSVC\14.16.27023\include\utility(405):
note: No constructor could take the source type, or constructor
overload resolution was ambiguous
..\examples\json_object\json.cpp(16): note: see reference to function
template instantiation 'std::pair<std::string,A>
std::make_pair<std::string,A>(_Ty1 &&,_Ty2 &&)' being compiled with
[
_Ty1=std::string,
_Ty2=A ]
Similar error for gcc
compiler.
When I remove std::mutex
from class OR don't push the object on std::vector
, then it compiles fine.
As pointed by P.W and hint provided by freakish I come up with below solution.
#include <iostream>
#include <mutex>
#include <vector>
#include <memory>
class A {
std::mutex mutex;
public:
A(){};
};
int main()
{
std::vector<std::pair<std::string,std::shared_ptr<A>>> aa;
A a;
//aa.push_back(std::make_pair(std::string("aa"),A()));
//aa.push_back(std::make_pair(std::string("aa"),a));
aa.push_back(std::make_pair(std::string("aa"),std::make_shared<A>()));
}
I modified my container to store smart pointer of object instead of object itself.