Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

{} uses copy constructor, while = does not #805

Closed
jllansford opened this issue Oct 27, 2017 · 8 comments · Fixed by #807
Closed

{} uses copy constructor, while = does not #805

jllansford opened this issue Oct 27, 2017 · 8 comments · Fixed by #807

Comments

@jllansford
Copy link

jllansford commented Oct 27, 2017

Just a little annoyance I encountered while writing to_json functions for a large number of in house classes. Ideally I'd like it if the {} operator behaved the same as the = operator.

Given the following code:

using json = nlohmann::json;

class A {
private:
	std::string          _val;

	// by including the mutex we've implicitly deleted our copy constructor 
	std::recursive_mutex _mutex;

public:
	A() : _val("Hello World") {};

	friend void to_json(json &j, const A &a) {
		j = {
			{"val", a._val}
		};
	}
};



int main(int argc, char* argv[]) {

	json j = {};
	A a;

        // This line compiles and runs completely fine.
        j["data"]["A"] =  a;

        //this line will fail to compile, due to the implicitly deleted A::A(const A&)
	j["data"] = {{"A", a}};
	
        std::cout << j.dump() << std::endl;
	return 0;
}
@theodelrieu
Copy link
Contributor

Could you paste the complete error output? Knowing where the copy happens would help a lot :)

@nlohmann
Copy link
Owner

Xcode:

main.cpp:36:24: error: call to implicitly-deleted copy constructor of 'A'
    j["data"] = {{"A", a}};
                       ^
main.cpp:13:26: note: copy constructor of 'A' is implicitly deleted because
      field '_mutex' has an inaccessible copy constructor
    std::recursive_mutex _mutex;
                         ^
./json.hpp:6785:22: note: passing argument to parameter 'args' here
    json_ref(Args... args)
                     ^
1 error generated.

@theodelrieu
Copy link
Contributor

Oops, missing forwarding references it seems

@nlohmann
Copy link
Owner

Aha? I have no idea how to fix this.

@theodelrieu
Copy link
Contributor

theodelrieu commented Oct 27, 2017

I'll fix it by tonight, if there is no surprises with json_ref.

@nlohmann
Copy link
Owner

Thanks a lot! I have no time right now to wrap my head around this...

@nlohmann
Copy link
Owner

@jllansford PR #807 fixed the issue. Could you please check if this works for you?

@jllansford
Copy link
Author

I've been away for a few days but got around to testing the fix today and it works great.

Thanks for the prompt reply and fix.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants