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

Method call on nullptr

Content

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

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
Timeweb

Let me recommend you the excellent hosting on which EVILEG is located.

For many years, Timeweb has been proving his stability.

For projects on Django I recommend VDS hosting

View Hosting
BN

C++ - Тест 003. Условия и циклы

  • Result:7points,
  • Rating points-10
G
  • G1ROG
  • Feb. 27, 2021, 9:30 a.m.

C++ - Тест 003. Условия и циклы

  • Result:28points,
  • Rating points-10
SG

C++ - Тест 003. Условия и циклы

  • Result:0points,
  • Rating points-10
Last comments
D

Django - Tutorial 001. Deploying a site on Django + PostgreSQL + Gunicorn + Nginx

А почему нельзя? Где можно об этом почитать? Киньте, пожалуйста, в меня ссылкой.
D

Django - Tutoral 049. Optimizing Django Performance with a Real Project

Огромное спасибо вам за статью! Для меня стали открытием select_related и prefetch_related
t
  • t1m4
  • Feb. 24, 2021, 2:56 a.m.

Django - Tutorial 052. Redefining a User Model

В данном случае я заходил под superuser но все равно не появлялись эти поля

Django - Tutorial 001. Deploying a site on Django + PostgreSQL + Gunicorn + Nginx

Поднял сервис с помощью systemd, вот по этому мануалу: https://habr.com/ru/post/501414/
t
  • t1m4
  • Feb. 23, 2021, 7:11 a.m.

Django - Tutorial 052. Redefining a User Model

А как дать ему эти права?
Now discuss on the forum
KM

как добавить списки в список, которые созданы динамически

import numpy as np from pprint import pprint import collections from itertools import chain import pandas as pd from itertools import islice import time from i…

Не отдаётся статика на виртуальной машине

В итоге выставил 775 на все файлы проекта и всё заработало. Но я не уверен, что так правильно.
P
  • Pisych
  • March 3, 2021, 1:06 a.m.

Вывод данных из связанных таблиц.

Не знаю, правильно ли... Но работает <body>{% for i in CatList %} <ul> <li><h3>{{i.title}}</h3></li>{% for j in ProdList %}<ul>{…
M

нужна помощь с проектом qt c++

дали задание, на несколько дней. собираюсь делать, но хотел бы получить помощь более опытных людей, чтобы подкорректировать себя и подстраховаться. каким образом это можно сделать? …

QScrollArea dynamically add QCheckBoxes

Всё правильно. Это просто спамер, который отправился в вечный бан.
About
Services
© EVILEG 2015-2020
Recommend hosting TIMEWEB