vector::push_back not work for non default constructor

后端 未结 4 1111
萌比男神i
萌比男神i 2021-01-28 13:26

i have a Controls class that have default constructor and copy constructor and other constructor ,and an assignment operator , and i want to create array of my cla

相关标签:
4条回答
  • 2021-01-28 14:05

    When using auto_ptr you should use release not get to pass the pointer to new owner:

    Not this in Controls::Controls(QLayout &Parent , string name , const int &Default_value):

    Layout.addWidget(Label.get() , 0 , 0);
    

    But that:

    Layout.addWidget(Label.release() , 0 , 0);
    

    Otherwise - your auto_ptr are deleting the pointers at the end of scope of this constructor.

    0 讨论(0)
  • 2021-01-28 14:09

    This has nothing to do with std::vector and non-default constructors. You did not provide the whole code, but I assume this is the continuation of the previous question.

    Your Controls::operator= is invalid, it creates copies of QWidgets, and puts them into brand new QLayout. Controls object that you pass to push_back is temporary object that is destroyed after the call and it's copy is put into vector. But destroyed object's QWidget members are put into QLayout, which is not destroyed and which is added to the widget you try to show (Panel). After temporary Controls object is destroyed, Panel->show() calls Panel's QLayout methods that try to access already deleted widgets.

    Do you really need to save copies of your Controls objects in your vector? If you store pointers, that would get rid of your problem. Why do you need that vector at all?

    And once again, do not use auto_ptr, it's deprecated and you don't need it to correctly manage deletion of QObjects.

    0 讨论(0)
  • 2021-01-28 14:14

    I'm not sure that you are implementing your copy semantics correctly, and the use of std::auto_ptr as a data member is kind of an "alert sign".

    Are your Controls really deep-copyable?

    Maybe you should just use scoped_ptr instead of auto_ptr data members, ban copy declaring private copy constructor and private operator=, and use vector<shared_ptr<Controls>> ?

    (Or use C++11 and move semantics, and so use unique_ptr instead of auto_ptr, and just use compiler automatically generated move operations?)

    0 讨论(0)
  • 2021-01-28 14:27

    Also, I think the problem is with your auto_ptr variables. You should check if it is really the way how you want to treat your object pointers. I would rather stick with the shared_ptr or unique_ptr. In the latter case however, you don't want to have copy constructor at all, as there could be only one owner of the pointers.

    C++ std::auto_ptr copy constructor

    0 讨论(0)
提交回复
热议问题