Evgenij LegotskojJuly 21, 2020, 2:31 a.m.

Method call on nullptr

Let's take a look at a small code example when a method is called on an object that is initialized with nullptr .

ADS

Sample code

We are given the following program code.

#include <iostream>

using namespace std;

struct X
{
    X* self()
    {
        cout << "call method of nullptr" << endl;

        if (!this)
        {
            cout << "object does not exist" << endl;
            return nullptr;
        }

        cout << "object exist" << endl;
        return this;
    }
};

int main()
{
    X* x = nullptr;
    if (x->self())
    {
        return 0;
    }

    return 0;
}

Explanation

Do you think the program will crash in this case? If not, what will be output to the console?

As a rule, the program will not crash in most cases. But this is unknown. This code is an example of undefined behavior, i.e. Undefined Behavior . The behavior of the program will be determined by the internal implementation of the compiler and will not give a guaranteed result. That is, the crash of the program and the correct execution of the program are equally correct answers.

What happens if the program functions properly?

Answer: The following message will be displayed in the console

call method of nullptr
object does not exist

That is, the method will be executed as a static method, as if we were referring to a static method of the class. This is possible due to the fact that the type of the object, the signature and the implementation of the called method are known. At the same time, access to the internal class variables is not performed. And checking for this allows you to verify whether the object exists. You can also do without this check, the code will still be executed until a part of the code that requires the created object is encountered.

Conclusion

However, this code is an example of undefined behavior - Undefined Behavior . Therefore, such tricks are highly discouraged when developing software. Because even if the code works now, it may stop working in the next version of the compiler. Therefore, think a few times before writing this.

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.
- company blog
Support the author Donate

Comments

Only authorized users can post comments.
Please, Log in or Sign up
Fornex

Let me recommend you a great European Fornex hosting.

Fornex has proven itself to be a stable host over the years.

For Django projects I recommend VPS hosting

Following the link you will receive a 5% discount on shared hosting services, dedicated servers, VPS and VPN

View Hosting
MP

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:60points,
  • Rating points-1
SI

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:60points,
  • Rating points-1
k

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:90points,
  • Rating points8
Last comments
H

Python: How to Test Internet Speed

There may be no animus franchise that opens with as dull-witted and satiating a ritual as Scream. As the shaping followers’s logo appears on wall, we rather enter upon hearing the ringing of a l…
A
  • Andrew
  • Jan. 12, 2022, 11:41 a.m.

Qt/C++ - Lesson 038. Switching between windows in the Qt

Здравствуйте, а как сделать чтобы второе и третье окно не сохраняли свои параметры а создавались заного? Только начинаю изучать прогграмирование и пишу протенькую игру сделал 2 окна, одно с меню…
j
  • juvf
  • Dec. 28, 2021, 11:56 p.m.

Deploying Qt and QML Applications on Linux and Windows

написал приложение, холоворд на qt виджетах, без qml. Из визарда QtCreator. Собрал кросскомпилятором. Нужно перенести на таргет. juvf@juvf-VirtualBox:~/qtWs/test/imx6/release$ ~/CQtDeploye…
AO

Qt/C++ - Lesson 023. Moving QGraphicsItem on QGraphicsScene with mouse help

А есть возможность передавать координаты классу, что-бы он рисвал, допустим линию?
q

Django - Tutorial 036. How to add authentication through social networks. VKontakte

Добавь в setting.py строку: SOCIAL_AUTH_VK_OAUTH2_API_VERSION = '5.81'
Now discuss on the forum
AB

Sorting the added QML elements in the ListModel

I am writing an alarm clock in QML, I am required to sort the alarms in ascending order (depending on the date or time (if there are several alarms on the same day). I've done the sorting …
VK

Как получить ссылку на обьект присылающий сигнал через сигнал/слот?

Вот и ответ: Спасибо Александру за подсказку. void Core::onLogin(QString m_login) { Worker *m_worker = qobject_cast (sender()); hashLogin.insert(m_login, m_wor…
v

подтвердить значение в SpinBox

Мне необходимо подтвердить значение в SpinBox нажатием клавиши Enter и перевести фокус на другое поле. self.doubleSpinBox.returnPressed.co nnect(self.pressedKeys) def pressedKeys(sel…

Сортировка по дате и времени QSortFilterProxyModel QSqlRelationalTableModel

Добрый день. Наследуйте модель сортировки от QSortFilterProxyModel и переопределите метод QSortFilterProxyModel::lessThan таким образом, чтобы вы забирали через индексы дату и в…

Как создать класс вызывающий функции по входному числу 0-255?

Вы в любом случае упрётесь в маршрутизацию сообщения от этих цифр 0-255 до вызова конкретных методов и функций. А все эти пляски метасистемой Qt в данном случае лишь усложнение кода. Если …
About
Services
© EVILEG 2015-2021
Recommend hosting TIMEWEB