Insert into vector having objects without copy constructor

后端 未结 4 1688
执笔经年
执笔经年 2020-12-08 10:53

I have a class whose copy constructors are explicitly deleted (because A uses pointers internally and I don\'t want to fall into shallow copy pitfalls):

clas         


        
4条回答
  •  独厮守ぢ
    2020-12-08 11:50

    I ran into this problem with an external library's class. I was getting,

    "Error C2280 ClassName::ClassName(const ClassName &)': attempting to reference a deleted function"

    I'm guessing that the class I was using had deleted its copy constructor. I couldn't add it to any std containers I knew of for my custom derived-class objects, which wrapped their object with some helpers of mine to help with initialization/error checks.

    I worked around this blocker with (risky) pointers.

    Basically, I transitioned to this:

    std::vector names;
    ClassName name("arg");
    ClassName name_ptr = &name;
    names.push_back(name_ptr);
    

    from this, originally:

    std::vector names;
    ClassName name("arg");
    names.push_back(name);
    

    Interesting to say, this was the first time coding with C++ that I've actually needed to use pointers for non-pointer-specific usage requirements due to no known alternative. That makes me worry that I may missed something fundamental within my own code.

    Maybe there's a better way to do this, but it's not on this question's list of answers yet...

    edit for Caveat:

    I should have mentioned this before, thanks aschepler; if you do this and the container you're using outlives the object, "bang, you're dead."

提交回复
热议问题