I’m trying to update a small utility application to a more modern C++ fashion, but I’m having problems using some Qt objects with std::shared_ptr, especially those that receive some other QWidget as a constructor argument.
For example:
private:
std::shared_ptr<QWidget> centralwidget;
std::shared_ptr<QVBoxLayout> verticalLayout;
public:
void setupUi(QMainWindow *MainWindow) // this pointer is a .get() from a shared_ptr
{
centralwidget = std::make_shared<QWidget>(new QWidget(MainWindow)); // compiles fine
verticalLayout = std::make_shared<QVBoxLayout>(new QVBoxLayout(centralwidget.get())); // does not compile
}
The compile error is:
Error 1 error C2664: ‘QVBoxLayout::QVBoxLayout(QWidget *)’ : cannot
convert parameter 1 from ‘QVBoxLayout *’ to ‘QWidget *’ e:\microsoft
visual studio 11.0\vc\include\memory 855
I cant seem to understand this error, I’m not converting anything, I’m just trying to create a QVBoxLayout object and passing a QWidget as its parent (like i would do with raw pointers).
The arguments to
std::make_sharedare passed to the constructor of the class you’re instantiating. So basically what you are doing is equivalent to:I think what you are trying to do is :
Have a look at the documentation of
std::make_shared(for example here). The whole point of this function is to allocate the reference count near the object instance in memory, so you have to let it do the allocation for you.