Search code examples
c++rapidjson

c++ attempting to reference a deleted function in non existing constructor (using rapidJson)


I'm currently getting this error: 'User::User(const User&)': attempting to reference a deleted function

The program passes a string value of an object into the class.

User Constructor:

User::User(string s){
    int size = s.length() + 1;
    char* cstr = new char[size];
    strcpy_s(cstr, size, s.c_str());
    user.Parse(cstr);
}

Main Loop:

int main(){
    //json equals something similar to this: "{\"body:{[{"user":1},{"user":1},{"user":1}]}\"}";
    const char * json;
    Document d;
    d.Parse(json);
    if (d.HasMember("body")) {
        if (d["body"].IsArray()) {
            for (SizeType i = 0; i < d["body"].Size(); i++) {
                string json = getJsonString(d["body"][i]);
                User u = User(json); \\this is where the error point to
                this->users.push_back(u);
            }
        }
    }
}

getJsonString function:

string getJsonString(Value& value) {
    StringBuffer buffer;
    buffer.Clear();
    Writer<StringBuffer> writer(buffer);
    value.Accept(writer);
    return string(buffer.GetString());
}

I search for a lot of explanation on this error but nothing seems to make sense to me. I think it has something to do with the vector array however it doesn't make sense to me as I'm not using a pointer or reference for any of the user value. It seems to point to the constructor however no pointer or reference is being passed through. I through by returning the string of the json, I wasn't using a pointer but maybe I actually am? I would be grateful for any explanation to what I am doing wrong.


Solution

  • User is not copyable; this means that:

    • User::User(const User&) (copy constructor) is private
    • or deleted (= delete;)
    • or deleted implicitly (e.g. class has non-copyable members, or inherits from a non-copyable class). Thank you Yksisarvinen for the comment

    This means you are not allowed to create a new User from another one.

    Then, if you want to store User objects in a vector (as you are "apparently" trying to do in your post, I say "apparently" because the posted code does not compile, I dunno who is this) you cannot store them by value, as the vector contained needs an accessible copy constructor.

    See std::vector:

    T must meet the requirements of CopyAssignable and CopyConstructible.

    However, you can store them as pointers:

    std::vector<std::shared_ptr<User>> users;
    users.push_back( std::shared_ptr<User>( new User( json ) );