Object Lifetime in C++ (Stack/Scope Lifetimes)

  Рет қаралды 157,292

The Cherno

The Cherno

7 жыл бұрын

Patreon ► / thecherno
Twitter ► / thecherno
Instagram ► / thecherno
Discord ► / discord
In this video we'll be talking about lifetimes in C++. This specifically refers to how long stack allocated variables will actually last for; that is, how long will their memory be "alive" until it automatically gets freed and cleaned up.
Series Playlist ► • C++
Thank you to the following Patreon supporters:
- Samuel Egger
Gear I use:
-----------------
BEST laptop for programming! ► geni.us/pakTES
My FAVOURITE keyboard for programming! ► geni.us/zNhB
FAVOURITE monitors for programming! ► geni.us/Ig6KBq
MAIN Camera ► geni.us/t6xyDRO
MAIN Lens ► geni.us/xGoDWT
Second Camera ► geni.us/CYUQ
Microphone ► geni.us/wqO6g7K

Пікірлер: 182
@hedgehog_fox
@hedgehog_fox 4 жыл бұрын
Cherno WE NEED A VIDEO OF YOU PLAYING YOUR GUITAR!
@foxtrotjeff
@foxtrotjeff 6 жыл бұрын
I'll click the like button even though you pointed the wrong direction. :)
@explorerofworlds512
@explorerofworlds512 4 жыл бұрын
He realized he confused whether the like button was on the right or the left only to realize that in video format he's is in the mirror anyways.
@RandomProduct
@RandomProduct Жыл бұрын
Man, you made this series while I was back in college, and holy shit do I wish I'd found it back then. I'd probably be in a much different place in my career today (namely, already in C++ game dev, not trying to pivot from C#) if I had. You make great videos, you isolate the topics very well, you go deep enough (including brushing on the assembly at times) to give a great understanding of what's happening, and you make it all super digestible. Thank you so much for this.
@Xx_McJasper_xX
@Xx_McJasper_xX 3 жыл бұрын
I'm watching the whole C++ playlist even though I already know most of what's being presented (enjoy that penny my view brings you, Cherno!). This video brought me something new though. Thanks for covering scoped pointers. Cool concept and I can't wait to get through the C++ tutorials and start the Game Engine series. Cheers!
@specialgorilla
@specialgorilla 3 жыл бұрын
Yo this was an absolute lifesaver, I was finally able to get my system up and running with this, thank you so much! Also I learned OpenGL exclusively from you. Great work my man.
@malarlinkeshwaran8347
@malarlinkeshwaran8347 6 жыл бұрын
Really like your series. Answered very well questions I had for years on C++ conventions. Particularly coming back to C++ from C#, the allocation on stack vs heap of classes....that is a major 💡 moment. Thanks
@TheRealZitroX
@TheRealZitroX 25 күн бұрын
It is a major speed boost
@kumwamd
@kumwamd 6 жыл бұрын
Great C++ video series! Your explanations are great. Keep up the good work! 👍
@arnsteinkvande703
@arnsteinkvande703 6 жыл бұрын
These videos are sooo great! Thanks man!
@mattgraves3709
@mattgraves3709 3 жыл бұрын
This particular video helped a lot of stuff come together for me dude... Thank you... from the bottom of my heart man, thank you.
@TG47GRG
@TG47GRG 5 жыл бұрын
Your hair looks great!! Thank you for uploading your videos. They are very helpful :)
@VarunArora14
@VarunArora14 4 жыл бұрын
Well that was something I didn't notice being a bit newbie. Thanks and keep making such videos on C++
@benjaminf.3760
@benjaminf.3760 6 жыл бұрын
Damn it man your videos are simply the best C++ explanation I could find. I struggled forever to understand scope lifetimes. huge thumbs up
@websurfer5283
@websurfer5283 6 жыл бұрын
Modularising the series FTW. I definitely like it done this way and not big 40 minute vids on subjects. Great series!! ps - point to your bottom left for like button. Its on the right on my screen so your bottom left facing the camera :).
@aquavitale3551
@aquavitale3551 5 жыл бұрын
The Like button on the left is probably relevant in Australia, I guess it's upside down as well. However, I've found the European one and clicked that.
@bigboygrumpy8821
@bigboygrumpy8821 2 жыл бұрын
You make c++ make sense and now I understand it better I was always overthinking a lot in c++ but you helped me out
@h.hristov
@h.hristov 7 жыл бұрын
Thanks for this video man. That scoped / smart / unique pointer trick is really cool and useful. I'm still a bit confused about that implicit conversion thing. I should re-watch that video haha
@TheSunscratch
@TheSunscratch 7 жыл бұрын
Hristo Hristov nice example of implicit constructors : en.cppreference.com/w/cpp/language/converting_constructor
@papundekel
@papundekel 7 жыл бұрын
its because of the conversion constructor (one which takes only one parameter)
@pedrodeazeredonogueira9661
@pedrodeazeredonogueira9661 2 жыл бұрын
i love you you literally saved my life 7 times this past few weeks
@lysdexic9129
@lysdexic9129 7 жыл бұрын
Have you considered doing a video on initialisation? Initialisation is a little confusing in C++11. In particular the Universal and Uniform approach.
@_TheDudeAbides_
@_TheDudeAbides_ 7 жыл бұрын
I think your videos are great and your way of speaking is very clear and good. Also, careful so you don't slap the cactus! ;-)
@tsaliponics5014
@tsaliponics5014 4 жыл бұрын
Thank you so much for this lesson. I got into cplus plus for a personal project and had a humongous debugging issue that made me question this life decision. So much doubt went into my kind because a variable i wanted to use throughout a program would simply chanhe. Being new i didnt know what area to even research in the first place. This helped a noob outd
@gunrunjk
@gunrunjk 6 жыл бұрын
Amazing instruction !!
@tsvetomirdenchev1440
@tsvetomirdenchev1440 7 жыл бұрын
TheCherno, thank you for the awesome series! I would recommend other users to try out running their executables against valgrind, which is a suite of debugging tools that can be useful for tracing issues with memory. This is how I got a better picture of the heap and stack concepts. Valgrind is available under Linux and MacOS, can you recommend any substitute for Windows users?
@mpenabad
@mpenabad 2 жыл бұрын
I was looking up wether std::vector stored the data, either in the stack or the heap, and found out that is was like you ScopedPtr. Greatly explained, as always!
@212Staff
@212Staff 7 жыл бұрын
Thank you, Cherno!
@informativecontent4778
@informativecontent4778 5 жыл бұрын
you really r the man!!!
@feraudyh
@feraudyh 6 жыл бұрын
One thing this does not address and it is a closely related subject is returning a class from a function and the attendant "return value optimisation"
@BangMaster96
@BangMaster96 5 жыл бұрын
Thank You SOOOOO Much!
@farzadtotonchi5585
@farzadtotonchi5585 7 жыл бұрын
good start!
@imaginaryvivid
@imaginaryvivid 2 жыл бұрын
The best C++ tutorial I've ever seen.
@jhashivam28
@jhashivam28 4 жыл бұрын
Cherno please make Data structures and algorithms series too...
@joshperry9468
@joshperry9468 4 жыл бұрын
Your videos are fantastic man, thanks. Quick one on stack scope. If you have a function that creates a var in local scope and returns it by value, is it the case that any caller of that function using the assignment operate will invoke the copy/move constructor for classes/structs or simply copy for primitive types, such that the returned var isn't actually released? And in some cases the compiler does NRVO and copy elision to optimize this process? Because in my experience a locally created variable returned by value can still be used by the caller - you won't get an unexpected released var in the stack frame above the function. This obviously does *not* apply with returning pointers to locally created vars - which is what you reference in the array case in the video. Is my thinking correct @The Cherno??
@raashidansari
@raashidansari 7 жыл бұрын
Whatever happened to your Log class that you talked about in earlier videos.
@alt0v14
@alt0v14 4 жыл бұрын
destructed :)
@Futureblur
@Futureblur 3 жыл бұрын
It went out of scope
@adryelgainza1530
@adryelgainza1530 3 жыл бұрын
The memory holding it was freed. It is now swimming in a salt lake in turkey. That beautiful log
@balumail75
@balumail75 5 жыл бұрын
Good explanation.
@farsanrashid5601
@farsanrashid5601 6 жыл бұрын
People watching this video google the term RAII, Cherno just described RAII in plain english without explicitly mentioning it. Good job cherno.
@kemptcode
@kemptcode 7 жыл бұрын
Yeah but how do i cook and season a pork roast shoulder?
@TheCherno
@TheCherno 7 жыл бұрын
+John Doe Cooking with Cherno (TM) is coming soon ;)
@MaeveFirstborn
@MaeveFirstborn 7 жыл бұрын
I'd actually watch that.
@suntzu1409
@suntzu1409 3 жыл бұрын
@@TheCherno Cooking with Charno (No offense intended)
@samdavepollard
@samdavepollard 3 жыл бұрын
LOL 42 videos in and finally, 'I need a haircut'. Many Thanks for sharing your knowledge. Superb series.
@user-mo3ji7lu2u
@user-mo3ji7lu2u 3 жыл бұрын
Thank you!
@pouria2728
@pouria2728 3 жыл бұрын
4:49 I really like this part
@nazar1744
@nazar1744 7 жыл бұрын
Nice video dude! Is there a way to measure the exact time your code needs to be executed? So that your can see if your optimizations did work or not.
@Silvan278
@Silvan278 7 жыл бұрын
Of course there is ;) Take a look at the c++ 11 header. It allows you to measure time up to nanosecond precision.
@nazar1744
@nazar1744 7 жыл бұрын
Jesus...the amount of libraries for C++ is over 9000. Thanks dude!
@dylanphoon8206
@dylanphoon8206 6 жыл бұрын
ITS OVER 9000!
@pedramgh2998
@pedramgh2998 4 жыл бұрын
Love ❤️ you cherno
@neutronx1384
@neutronx1384 3 жыл бұрын
This explained A LOT
@Byynx
@Byynx 9 ай бұрын
Great Video.
@JoCS11152
@JoCS11152 Жыл бұрын
fuck men really u dont know how i apreciatte this. today i teach to my friend a lot of stack and heap just by seeing this video and the "stack vs heap". teaching something, improve yout knowledge, but also it feels good to spread the good
@spyroninja
@spyroninja 6 жыл бұрын
Great video and I love this entire playlist/channel...BUT that guitar on the table against the wall in the back makes me SO NERVOUS.
@1Naif
@1Naif 7 жыл бұрын
You are awesome
@Marcus-yc3ib
@Marcus-yc3ib 6 ай бұрын
Thank you very much.
@cooltuque
@cooltuque 2 жыл бұрын
Best. Tutorial. Ever.
@lukefox836
@lukefox836 5 жыл бұрын
Your fingers have a nice rhythm like they enjoy coding ... can't wait for that stage.
@albinbergstrand9416
@albinbergstrand9416 5 жыл бұрын
2:06 in the words of big smoke
@luisantonioreyes9375
@luisantonioreyes9375 4 жыл бұрын
How can you know in the "Memory Window" of Visual Studio where are the heap and stack located?
@szinton
@szinton 7 жыл бұрын
Not really about the video, but about classes: If I have a destructor in my class like ~Entity() does it change anything if I write something in the brackets?
@oraviram
@oraviram 7 жыл бұрын
Are you asking if constructors can have parameters? If so, then the answer is no.
@szinton
@szinton 7 жыл бұрын
Yea, just wanted to know that, thanks =)
@Raymoclaus
@Raymoclaus 7 жыл бұрын
@Or Aviram, I'm just gonna clarify your comment and clear up any confusion for anyone reading it. I think you meant to say destructors can't have parameters. Probably just a typo, but yeh constructors can have parameters.
@oraviram
@oraviram 7 жыл бұрын
Yeah, that's what I meant. :P
@andrearocca2715
@andrearocca2715 2 жыл бұрын
Hi Cherno! Thank's for this video. I have a question for you. Could you please clarify how Heap and Stack are related to the the RAM and caches?
@jarppa1390
@jarppa1390 Жыл бұрын
Ram is physical memory in a computer. If you have a computer program running on a PC with operating system, the OS hides all interractions between the RAM and the program with virtual memory. I.E program is only aware of the virtual memory that the OS provides. Then what is stack? It is a section of that virtual memory that the program uses to handle static memory allocations. static means that the size is known when the code is compiled to an executable. Heap is part of the virtual memory where the program can make dynamic memory allocations. Dynamic means that the needed memory size is known when the executable is running. Cache is a term used when you have two programs running at the same time: server and client. And the client asks server to perform some operation for example calculate what is 2+2 and return the result back. When client gets the result 4 it can assume that the result will also be 4 next time so it can cache the ressult to a variable and next time the user of the client program needs to calculate 2+2 the client can return the cached answer instead of asking the server again. So all in all they dont really relate at all.
@justred2337
@justred2337 7 жыл бұрын
Hey TheCherno, nice video! Just a quick question... Are you going to continue the 2d game programming series?
@xnoor-gg3362
@xnoor-gg3362 5 жыл бұрын
that was a good example of stack vs heap;
@yoavmor9002
@yoavmor9002 9 ай бұрын
In Windows Sockets, the API asks you to call some function at the start of your program and another at the end. It is very useful to create an empty class that calls those functions in the constr. And destr.... I also made the constr. of the other classes I built to work with Sockets private, and made that class friends with them, so that it is guaranteed that I create this object before using the Winsock tools
@teacup3000
@teacup3000 6 жыл бұрын
can you do a hair tutorial? xD
@inx1819
@inx1819 3 жыл бұрын
new hair series
@mattgraves3709
@mattgraves3709 3 жыл бұрын
Hair++ Im in
@NeoKailthas
@NeoKailthas 3 жыл бұрын
we're going to have a real chat about that. proceeds to pull out a silver sword. lol
@phillipvance864
@phillipvance864 5 жыл бұрын
to get a pointer to the array could you do this?: int* create_array() { static int* result[50]; return result; } In this case, wouldn't static allow the result to live outside of the function scope? The follow up is, do I need to free this memory with delete? This is created on the Stack I think, but is this still a memory leak since this pointer will continue living outside of its original scope?
@drb073
@drb073 4 жыл бұрын
1. static in a functions means that every times you call this function this array will be the same. 2. Your code is not valid. You could write this code: int* create_array() { static int result[50]; return result; } but every time you use this function you get the same array. Look at this code: int * a = create_array(); int * b = create_array(); a[0] = 5; b[1] = 10; std::cout
@nighma
@nighma 7 жыл бұрын
Hi Thanks for this serie (again). May be you could lower the volume of the music a bit ;)
@serkanozturk4217
@serkanozturk4217 Жыл бұрын
Personal Notes: -when you create an object in a function by stack allocation, if you try to return that object, it is wrong since it is deleted after scope(important: check if it is still a problem if you assign it to another variable when you call that function) -You can create a scoped pointer class which takes the object’s pointer (works as a wrapper) and helps it to automatically be deleted when scope ends. This is done by overriding destructor method, which means even if it is allocated on heap, the object’s destructor is called but it is not able to delete it since the data is not on stack. (Somewhat confusing, check the video)
@monishkumardurairaj3038
@monishkumardurairaj3038 5 жыл бұрын
does entity* e=new entity();here the constructor is called directly inside which during the member initialization amount of memory is calculated. is same as entity*e= new entity;here is have said the amount of memory needed by saying it is entity type and new keyword is used to call the constructor. is that right??someone correct me if am wrong.
@explorerofworlds512
@explorerofworlds512 4 жыл бұрын
"People have complaining about me using new and not smart pointers and teaching bad C++ We're about to have a real chat about that by the way." Did anyone else just feel like Cherno just put us in timeout.
@gaderishi
@gaderishi 8 ай бұрын
Anyone who said that he teaches bad , should recheck their scope
@johnadams7843
@johnadams7843 5 жыл бұрын
at 5:25 wouldn't making the array, static int array[50] also be a good solution?
@johnadams7843
@johnadams7843 5 жыл бұрын
@Peterolen you're right, that's a good point
@rockerirwin
@rockerirwin 6 жыл бұрын
as a side note: arrays in c/c++ are allways passed by reference
@MichaelYoussry
@MichaelYoussry 7 жыл бұрын
How can I access the unique ptr from the standard library?
@baaryl
@baaryl 7 жыл бұрын
First of all you have to include "memory" to your app. Next step is access it in std namespace. #include #include int main(int argc, char** argv){ std::unique_ptr name = std::make_unique(10); //or std::unique_ptr name2 (new int(10)); return 0; }
@patricktorgerson5810
@patricktorgerson5810 7 жыл бұрын
First, the internet exists, google it, you would get the answer much faster. Second, #include std::unique_ptr ptr;
@chieeyeoh6204
@chieeyeoh6204 Жыл бұрын
Timer is definitely one important use case!
@theprav1010
@theprav1010 4 жыл бұрын
What is the difference between void CreateArray(int* array) and void CreateArray(int& array), from my beginner knowledge, it should still be able to read from that address, right?
@alen7648
@alen7648 5 жыл бұрын
What do you think of euler project ?
@VapidVial
@VapidVial 4 жыл бұрын
I cried with the caption in 9.52 "The Reds are coming soon", sad soviet hymn noises
@dudeperforming4188
@dudeperforming4188 7 жыл бұрын
Waiting for game engine series.
@Khantia
@Khantia 2 жыл бұрын
I actually had to experiment with this myself, because I didn't notice that EntityPtr e = new Entity(); instead of new EntityPtr(); But I understood why it's acting the way it is after noticing that :D
@alltheway99
@alltheway99 4 жыл бұрын
Wrong, in case you thought is right, is wrong ... 😂😂 Dangling pointer
@ilyboc
@ilyboc 4 жыл бұрын
a video about mutex pliz (I ll go check if it exists already)
@andy-yh8gb
@andy-yh8gb 6 ай бұрын
Can you make video on namespaces too?
@antoniopafundi3455
@antoniopafundi3455 6 жыл бұрын
Why expression at 7:50 are the same? calling new inside the constructor is ok, but the other i ve not clear
@mohokhachai
@mohokhachai 10 ай бұрын
Including is for header wheras using is for namespace
@Rickilicious
@Rickilicious 4 жыл бұрын
that moment when you tell me i was wrong for thinking what you said was true @4:55 :( ive been scowled at
@xrafter
@xrafter 4 жыл бұрын
Don't trust the cherno. Trust the community
@balumail75
@balumail75 5 жыл бұрын
Can we store object in stack?
@giancedrick507
@giancedrick507 4 жыл бұрын
I spent the whole video looking at your hair
@edcarloorgel
@edcarloorgel 7 жыл бұрын
may i have one of your gitars?
@anis1930
@anis1930 6 жыл бұрын
whats implicit about that i mean the constructor has a Entity *pointer as parameter and the new return an address to an Entity so wheres the implicit convertion?
@approximately_3.14
@approximately_3.14 Жыл бұрын
use the #include std::unique_ptr entityptr(new Entity); for memory leak , this one a new scoped pointer
@pedramgh2998
@pedramgh2998 4 жыл бұрын
‎‏I believe that many of the members of this channel tend to get to know your personal life as well, because we all love you and appreciate your efforts as a teacher. please make a video about your own job, workplace, home and family 🌹. I know the time you spend on producing these great tutorials is very valuable, so thank you again.
@melgdelly1342
@melgdelly1342 5 жыл бұрын
Its in the middle, dude XD
@slap_my_hand
@slap_my_hand 7 жыл бұрын
Aaaaaaaaand it's gone.
@abderezakabidi4510
@abderezakabidi4510 3 жыл бұрын
I click the like button even before I finish the video,
@EchoVids2u
@EchoVids2u 2 жыл бұрын
So my Question is why use a unique pointer when you can just allocate it to the stack. Both will delete once out of scope.
@DonaldTamMisterDee
@DonaldTamMisterDee 2 жыл бұрын
unique ptr gets destroyed out of scope but the object that the ptr is pointing to is not destroyed when you allocate objects on the stack, you can only pass objects into functions via copy, and not reference, which might not be performant for big objects sometimes you may also want the object to outlive the lexical scope where it has been declared, in which case you would use a pointer like unique ptr
@nia5370
@nia5370 2 жыл бұрын
So order for an object to be in the stack, its size should be known at compile time (some compilers have extensions but its not in the c++ standard). More often than not, you'd have unique_ptr members in classes than functions returning a unique_ptr. Data that are loaded in and/or change during runtime usually would have its resources allocated in the heap. You probably want such data get automatically freed when it goes out of scope so no memory is being leaked. E.g. Resources like image and audio, containers, data structures, are all good candidates for having a unique_ptr to the raw allocated memory so it gets automatically freed when the encapsulating object is destroyed.
@febranom3567
@febranom3567 Жыл бұрын
Hi, I'm running some test which I create a class with private variable int X (not pointer), and a function that return X address. I'm trying to see if X deallocate or not coz i'm sure it does, But there's something weird happen when I create pointer P outside scope, and then create Object O inside scope and assign X address to P. At the end of the scope O's destructor is called so member variable should deallocate right?. But weirdly P still have the address to X and its value. So whats happen? I thought its gonna be nullptr but no. I couldn't really grasp the situation. But I think is that when memory get deallocated that memory is free to use but the value is still in it until something use that memory and overwrite it. Is that true or no?
@febranom3567
@febranom3567 Жыл бұрын
Or that the moment I assign stack address to a pointer It become heap allocated and not deallocate automatically?
@qandos-nour
@qandos-nour 4 жыл бұрын
Mashaallah very fast typing
@xrafter
@xrafter 4 жыл бұрын
Will fast typing need relax and patience
@abx4t
@abx4t 5 ай бұрын
~1kb / smart pointer is left on the heap when the data it references goes out of scope. You all should Think about that and consider how that affects optimization. Smart pointers are incredibly useful, but they are not and can never be fully optimized. The 'new' keyword has its place and is valid when properly used.
@aleksandarfranc1094
@aleksandarfranc1094 5 жыл бұрын
So i ckecked memory after going out of funtion to see does it delete the memory of array that is on stack and i doesnt!! Still in memory all elements of array: int* createAray() { int array[50]; for (int i = 0; i < 50; i++) array[i] = 4 ; return array; } int main() { int * arr = createAray(); std::cout
@nmamano
@nmamano 5 жыл бұрын
When an array is "deleted", the memory where it was stored is not actually immediately used for something else. It is simply marked as "free" to be used when necessary. So if you check memory right after it is deleted, it is still there, but it might be overwritten at any time with new data (this is true for space allocated both in the stack and in the heap). In fact, it is a typical bug to use memory that has already been deleted without noticing, and the program works fine for a while until you change something that seems completely unrelated and that suddenly breaks all kind of things. These are notoriously hard to fix.
@aleksandarfranc1094
@aleksandarfranc1094 5 жыл бұрын
@@nmamano Thanks BRO! :D
@cern1999sb
@cern1999sb 4 жыл бұрын
In real life you can just yank books out of a stack. Hmmm, stack.Yank(index);
@mohokhachai
@mohokhachai 10 ай бұрын
You are too smart
@iseraid1504
@iseraid1504 2 жыл бұрын
That's probably too late to ask questions since the video is 4 years old, but is it right that the smartPointer usage covered by you is kind of similar to stack allocation, just being made in terms of a heap and having it's purpose only for educational reasons? I mean, stack allocation does the same thing but faster, so there is not much point in smart pointer (see what I did here) if we don't want to bring our object outside the scope and delete it later automatically under some conditions?
@sauravsharma4937
@sauravsharma4937 Жыл бұрын
Can someone explain how ScopedPtr e = new Entity(); working From what little knowledge I have, left side is a normal variable, how a pointer is assigned to it
@jarppa1390
@jarppa1390 Жыл бұрын
ScopedPtr has a constructor which accepts Entity* as an argument, and the constructor is smart enough to do an implicit cast here. That code has equal behaviour to ScopedPtr e(new Entity());
@haykav
@haykav 6 жыл бұрын
I need a haircut too it's getting out of hand
@teiroberts5330
@teiroberts5330 6 жыл бұрын
Hey int, im out of scope, im taking you with me
@rishadkt9451
@rishadkt9451 2 жыл бұрын
int* getame(){ int array[5]; array[4] = 2123; std::cout
@flamez5493
@flamez5493 2 жыл бұрын
Problem here is that we are returning an address which may not exist in memory after function call/scope is over. Although it gives the output, it is considered as bad practice(?) and may result in further problems down the line when allocating memory in stack. I am a mostly beginner myself so i hope someone more adept can jump in and say if i am wrong. ngl i also find it extremely weird that it still outputted a value and not a garbage one.
@marilynman
@marilynman 2 жыл бұрын
@@flamez5493 By a garbage one, do you mean the second value? If so, it is because the output is not an array but a single value (a[4]).
@jscorpio1987
@jscorpio1987 4 жыл бұрын
I don’t know what everyone else is talking about with him pointing in the wrong direction for the like button, but on my device the like button is exactly where he pointed.
@xrafter
@xrafter 4 жыл бұрын
It have to be in different locations depends in your language
@levanfirtskhalava3836
@levanfirtskhalava3836 5 жыл бұрын
char* GetChar() { char* ptr = (char*)"Leonsius"; return ptr; } why it's work I mean when the function get out of scope the value of ptr is not destroyed { char* Name = GetChar(); // Valid declaration } int* GetInt() { int Array[50]; return Array; } but it's not work { int *A = GetInt(); // Invalid declaration } is there something different for string literal
@KostasOreopoulos
@KostasOreopoulos 5 жыл бұрын
You can watch the video on String Literals and constant memory (video 33 in the playlist)
@levanfirtskhalava3836
@levanfirtskhalava3836 5 жыл бұрын
@@KostasOreopoulos Thank you
@levanfirtskhalava3836
@levanfirtskhalava3836 5 жыл бұрын
Reason is: char* name = (char*) "Leonsius"; // this is String literal and it's storage in const data segment. the same reason without cast it's necessary const key word
Stack vs Heap Memory in C++
19:31
The Cherno
Рет қаралды 560 М.
Sigma Kid Hair #funny #sigma #comedy
00:33
CRAZY GREAPA
Рет қаралды 39 МЛН
Inside Out 2: Who is the strongest? Joy vs Envy vs Anger #shorts #animation
00:22
Playing hide and seek with my dog 🐶
00:25
Zach King
Рет қаралды 36 МЛН
Precompiled Headers in C++
21:30
The Cherno
Рет қаралды 154 М.
SINGLETONS in C++
19:16
The Cherno
Рет қаралды 197 М.
WHY did this C++ code FAIL?
38:10
The Cherno
Рет қаралды 240 М.
CONST in C++
12:54
The Cherno
Рет қаралды 398 М.
Type Punning in C++
13:20
The Cherno
Рет қаралды 155 М.
OPERATORS and OPERATOR OVERLOADING in C++
12:44
The Cherno
Рет қаралды 367 М.
Faster than Rust and C++: the PERFECT hash table
33:52
strager
Рет қаралды 531 М.
are "smart pointers" actually smart?
9:44
Low Level Learning
Рет қаралды 72 М.
Sigma Kid Hair #funny #sigma #comedy
00:33
CRAZY GREAPA
Рет қаралды 39 МЛН