0
0
0142016-04-13 22:51:17
Qt
014, 2016-04-13 22:51:17

How does the placement operator new work?

In Schlee's book Qt 5.3 there is an example of a program where an unusual notation of the new operator is used, on which I "hung". They write that this is an allocating operator, as I understand it, they can create and initialize pre-allocated memory. But Schlee's record of this operator in the problem somehow does not fit into this.

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    //Widget w;
    //w.show();
    QTextEdit txt;
    QFont fnt("Lucida Console", 12, QFont::Normal);
    txt.document()->setDefaultFont(fnt);

    new SyntaxHighLigther(txt.document()); // Вот она!!!

    QPalette pal = txt.palette();
    pal.setColor(QPalette::Base, Qt::darkBlue);
    pal.setColor(QPalette::Text, Qt::yellow);
    txt.setPalette(pal);

    txt.show();
    txt.resize(640, 480);

    QFile file("syntaxhighlighter.cpp");
    file.open(QFile::ReadOnly);
    txt.setPlainText(file.readAll());

    return a.exec();

This entry is not clear: new SyntaxHighLigther(txt.document());
SyntaxHighLigther is a class whose object has not been created, that is, a new object is created and initialized, but WHERE is it written? After all, there is nothing on the left side of the new operator.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
MiiNiPaa, 2016-04-13
@014

This is not hosting new. This is a normal object creation. The highlighter's constructor registers itself with the parent and the parent is responsible for removing it, so the result of new-expression is not used.
Placement new looks like this:
To understand how placement new works, you need to understand the difference between new-expression and the new operator. new-expression does things:
The allocating operator new takes as a parameter a pointer to the already allocated memory and simply returns it.

A
abcd0x00, 2016-04-14
@abcd0x00

but WHERE does it record?

This is a mistake in the book. Such happen at jambs of publishing house.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question