Похожие чаты

So i guess casting the return of any function that

return a pointer is not important as long as you store in the corresponding pointer type that you wanna work with , im correct ?

36 ответов

39 просмотров

Casting is not required at all. In fact it is not recommended because you repeat yourself.

VD
Casting is not required at all. In fact it is not ...

In C, yes, in C++, it is required. Reason is, in C++, any pointer, T*, can be implicitly converted to a void*, but an explicit cast is required to convert from void* to a point of a specific data type, T*.

VD
Casting is not required at all. In fact it is not ...

In C, yes, in C++, it is required. Reason is, in C++, any pointer, T*, can be implicitly converted to a void*, but an explicit cast is required to convert from void* to a pointer of a specific type, T*.

VD
Why would you use malloc in C++?

Simplest way to allocate 😎

Thomas
Simplest way to allocate 😎

new is much more simpler than malloc.

²
yes but no

That definitely clarified a lot for me

VD
That definitely clarified a lot for me

new its c++ thing malloc its more c thing than c++

²
new its c++ thing malloc its more c thing than c++

And your point is? I said new should be preferred in C++.

VD
Casting is not required at all. In fact it is not ...

gcc, clang and other "compilers" perform automatic type conversion, and its not portable for all systems. BTW, turning off this feature show how the compiler works and improve our skill

void
gcc, clang and other "compilers" perform automatic...

C99 and beyond requires implicit casting from void* to any other data pointer. So if an implementation doesn't support it, it is not standard compliant. When an implicit conversion is supported and it is lossless, there is no reason why you should make it an explicit cast. You are just repeating yourself with no added benefit.

VD
Why would you use malloc in C++?

I would not, but but some people do (just check Q&A sites) and it is provided by the standard, so the clarification had to be made.

VD
Why would you use malloc in C++?

Oh, to build onto my previous answer, some implementations of new used to (still do?) us malloc internally for the actual memory allocation. There are people who build highly custom memory allocation facilities for given environments and constraints, and some might overload new and delete. You can be sure that for those cases, they will probably use malloc internally at some point, cause the whole point is to provide alternatives for the default new and delete. That is a pretty solid use case for malloc and free in C++.

VD
C99 and beyond requires implicit casting from void...

Not all systems are standard compliant, lot have only "some" compatibility

Kenshin Himura
Oh, to build onto my previous answer, some impleme...

I agree. But most of the people who write their own allocators or overload operator new (the only ones who use malloc) would already know that they have to use an explicit cast for the return value from malloc

void
Not all systems are standard compliant, lot have o...

Can you give me an example of a system where the implicit conversion from void* to a data pointer of any type fails. I am really curious because this is so fundamental for the working of everything from an written in C to embedded and IoT world.

Manav | avoid unnecessary messaging me
Why not just use mmap, VirtualAlloc, etc?

First thing to ask in such scenarios is, are they general purpose memory allocators, like malloc, or do they serve a very specific use case? Do they suit the use case for the memory allocation scheme one desires? Then wrap them in a proper RAII interface and use them to your content. However, remember, we are talking about why someone would use malloc in C++ instead of operator new, hence the explanation in my previous message. Can mmap and VirtualAlloc be used to develop a general purpose operator new that is then provided as part of a standards compliant C++ implementation? I mentioned that some implementations of the default C++ operator new used to (still do?) use malloc internally for the actual memory allocation. Your two functions serve specific use cases, while malloc is more general and available. This is a simple yet interesting thread on this very topic, https://www.gamedev.net/forums/topic/708119-two-questions-regarding-virtualalloc-windows-and-mmap-linux/

Kenshin Himura
First thing to ask in such scenarios is, are they ...

"proper" and "RAII" at the same time heh, seems kind of... paradoxical

Kenshin Himura
How? 🤔

I don't consider RAII to be "proper"

Thomas
I don't consider RAII to be "proper"

What do you consider it to be?

VD
Can you give me an example of a system where the i...

8 bit pic microcontrollers. They use memory bank approach with several bits of selection inside the main register. When you use void* to encapsulate or hide data, it will be rougly translate for the address of that specific bank. You must use far void * to force the compiler will save those bits of bank selection. That obscure bugs gave me gray hair 😆

Kenshin Himura
First thing to ask in such scenarios is, are they ...

I see your point but I think you meant malloc being more accessible instead of general since mmap, VirtualAlloc, these functions get memory directly from the operating system. To be exact glibc's malloc implementation has a structure called arena which contains linked list of sub divided memory regions (called a chunk) called a free list. These chunks are what given to the application when memory is requested.

Thomas
garbage

Interesting. Well, it is the major bedrock of sane and safe C++ as far as system resources are concerned, so I strongly disagree with you. However, to each his own, though I would be interested in hearing how you personally deal with the scenarios it is usually employed in. Hold on. Do you use C++, or are you on this channel for C?

Kenshin Himura
Interesting. Well, it is the major bedrock of san...

I do use C++ when I have to, but I don't really use most of the features (constructors, destructors, templates, ...)

Kenshin Himura
Interesting. Well, it is the major bedrock of san...

I generally use DoD-style approaches where possible, so I use shared lifetimes and multiple allocators

Thomas
I do use C++ when I have to, but I don't really us...

Those are the features you don't use or the ones you do use?

Thomas
I do use C++ when I have to, but I don't really us...

Ah. This explains your unappreciation for RAII.

Похожие вопросы

Обсуждают сегодня

Добрый день. Хочу сделать отрисовку по команде на панели. Почему-то рисуется только при втором вызове. С чем может быть связано, не подскажете? procedure TForm1.FormDblClick(...
Kirill Filippenok
20
а зачем этот вопрос для удаления из чата?
Mёdkinson Medvezhkin
63
А почему в си некоторые вещи работают с двойными кавычками некоторые с одинарными? Нельзя было все сделать с одними или чтоб работало с разными? например чтоб выводить строки ...
.
15
using next image component with s3 image: "url" parameter is valid but upstream response is invalid code: <Image fill src={s...
Fasil
3
Всем привет! Нужен совет от опытных. Переношу свой проект с Делфи 10.2 Токио на Лазарус 3.2 установленный через инсталлятор fpcupdeluxe-x86_64-win64. При импортировании проект...
Дмитрий Завгородний
7
Всем привет! procedure TForm1.FormCreate(Sender: TObject); type TStartEnd = record S: Byte; E: Byte; end; var a, b: TStartEnd; begin {1} a.S := 1; {2} a.E := 2; ...
Руслан Михайлович
10
Всем привет!) я тут новенький и пытаюсь освоить evolution методом тыка. У меня при переходе между папками файлов выскакивают вот такие уведомления Можете подсказать как их от...
Диман Samoed
10
Эх кто-то пришел и весь праздник испортил :( You need complex FBX scene importing setup to change things on import? good luck with that. You need navigation and pathfinding? g...
Serg Gini
5
Friends, how can I find my Wazirx wallet address?
Silm Silm
31
Всем привет! Подскажите. Я написал приложение на Delphi 10.2 Tokyo под Windows 10. И передо мной стал вопрос о том чтобы сделать это приложение кроссплатформенным (под Linux и...
Дмитрий Завгородний
24
Карта сайта