Sign in to follow this  
SeraphLance

C++ Avoiding accidental allocations (and copies)

Recommended Posts

After seeing this talk (and combined with similar experiences in other languages), I got to thinking just how many times I pointlessly copy variables around.  I'm sure it's a lot, and I'm sure more experienced C++ programmers are better at catching these things (especially given how off-handed he remarks these -- like they're "duh" to everyone in the room), but it feels like I'm a bit lost as to how to actually find these sorts of mistakes.  Right now it sort of feels like an "experience through code review" thing, and that's a bit disconcerting.  Are there tools or techniques to track this sort of thing, so that I can find whether I'm spuriously making copies where I didn't intend to?

In context, the very first example he gives is the sort of thing I'd do if I thought I was being clever.

Share this post


Link to post
Share on other sites
On 14/10/2017 at 3:12 AM, Hodgman said:

Pretty much any complex class (where copying would be an issue) of mine will inherit from NonCopyable by default. If at some point later I actually run into a situation where I need to copy or move them, which honestly is actually very rare, I'll remove the NonCopyable base and actually think about the problem  

Also, just say no to string processing in C++ ;D

Agree.

A more modernish version of these classes would be just to declare the constructors deleted instead of making them private and having no definition. There, it makes also no interest to put them in a public or private section.

Also, note that all inherited classes can inherit in a protected way, thus not perverting the IS-A inheritance idiom.

Edited by _Silence_

Share this post


Link to post
Share on other sites

If a type is literally non-copyable due to its semantics or other constraints, then you should certainly delete the copy constructor and assignment operators (or otherwise hide them if you're not using C++11).

Otherwise, just implement the proper behavior and use a profiler to determine if you're performing extra copies and they're causing performance issues. If so, think about how you can optimize the copy, or prevent the copies from occurring at the specific places in code where they're a problem. Don't assume ahead of time there will be a problem, or change the semantics of the type to fix a usage issue. Just fix the usage if, when, and where it becomes a problem.

To address the original question, I personally like to think in terms of a value vs reference type dichotomy. One key difference between them is that value types are copy/move assignable, while reference types are not. Note that copy/move construction is still fine; you're just not allowed to assign to an already constructed instance. I adopted this mindset over the years because I found that the issue with copy/move semantics isn't that their implementations are too expensive or prohibitive, but rather that I wasn't considering the semantics of the type as a whole. Once that was fixed, the issues either disappeared completely, or I was better able to focus my efforts in the right place.

Edited by Zipster

Share this post


Link to post
Share on other sites

I do like the idea of just inheriting from a non-copyable base object as a safety net.  It at least solves a subset of potential problems.

Does anyone use any more dynamic approaches?  I know you can overload global new, but that seems a bit hole-y, since external libraries might use C or OS-allocation functions, and I have no idea what the standard libraries do under the hood.  That also seems really noisy because it's global.

43 minutes ago, Zipster said:

To address the original question, I personally like to think in terms of a value vs reference type dichotomy. One key difference between them is that value types are copy/move assignable, while reference types are not. Note that copy/move construction is still fine; you're just not allowed to assign to an already constructed instance. I adopted this mindset over the years because I found that the issue with copy/move semantics isn't that their implementations are too expensive or prohibitive, but rather that I wasn't considering the semantics of the type as a whole. Once that was fixed, the issues either disappeared completely, or I was better able to focus my efforts in the right place.

That's sort of the approach I've traditionally taken.  But then in the video linked I saw the equivalent of this:

class Foo
{
public:
	std::string m_a;
	std::string m_b
	Foo( const std::string& a, const std::string& b) : m_a(a), m_b(b) {}
}

If I were writing an object that took two strings prior to this video, I might write it like that.  I would think "okay, I don't need to mutate the strings, so I may as well express the parameters as const.  Since I don't want a straight copy of the string, I'm going to pass a reference".  If I had actually written this code, I probably would never have known that it copies.  In fact, I wouldn't have even thought to look at it.

In fact, the whole "take a reference to avoid a copy" mentality is so ingrained into my head that I don't even know why it copies.

...Or at least I didn't.  The irony of this is that I realized after writing that last line that the copy is made because the actual class member is a string, the copy is because of the actual initialization of the class member.  I probably wouldn't have made that sort of mistake in retrospect, but I obviously (given this thread) wouldn't have seen the mistake in code review of someone else's code, so I guess the question still stands.

Edited by SeraphLance

Share this post


Link to post
Share on other sites
20 minutes ago, SeraphLance said:

If I were writing an object that took two strings prior to this video, I might write it like that.  I would think "okay, I don't need to mutate the strings, so I may as well express the parameters as const.  Since I don't want a straight copy of the string, I'm going to pass a reference".  If I had actually written this code, I probably would never have known that it copies.  In fact, I wouldn't have even thought to look at it.

In fact, the whole "take a reference to avoid a copy" mentality is so ingrained into my head that I don't even know why it copies.

...Or at least I didn't.  The irony of this is that I realized after writing that last line that the copy is made because the actual class member is a string, the copy is because of the actual initialization of the class member.  I probably wouldn't have made that sort of mistake in retrospect, but I obviously (given this thread) wouldn't have seen the mistake in code review of someone else's code, so I guess the question still stands.

That's the thing though, the fact that the strings are copied is due to the implementation details of the type. It could just as easily printed the strings and not made its own copy at all. There's no way to tell from the declaration of the type exactly what it's going to do with those strings (assuming the constructor wasn't defined inline), so what can you really do about it? It's not as though you can remove the copy if the type really needs it. Either way, the implementation should be considered private and separate from the traits of the type itself.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Announcements

  • Forum Statistics

    • Total Topics
      628400
    • Total Posts
      2982449
  • Similar Content

    • By RidiculousName
      So I have a class next semester where I need to learn C++. I'll be going through the class textbook too of course, but I hate textbooks because I learn much better by programming than taking notes. I understand there's got to be some reading just to understand the syntax, but I have trouble remembering much from a whole chapter before programming. I prefer to work with smaller bits of information and gradually expand.
      So my question is, how could I learn C++ in smaller bits?
    • By rXpSwiss
      Hello,
      I am sending compressed json data from the UE4 client to a C++ server made with boost.
      I am using ZLib to compress and decompress all json but it doesn't work. I am now encoding it in base64 to avoid some issues but that doesn't change a thing.
      I currently stopped trying to send the data and I am writing it in a file from the client and trying to read the file and decompress on the server side.
      When the server is trying to decompress it I get an error from ZLib : zlib error: iostream error
      My question is the following : Did anyone manage to compress and decompress data between a UE4 client and a C++ server ?
      I cannot really configure anything on the server side (because boost has its ZLib compressor) and I don't know what is wrong with the decompression.
      Any idea ?
      rXp
    • By noodleBowl
      So I have some quick questions about constructors and pointers

      Question on constructors:
      1. I'm working on this Sprite class and in general sprites need some kind of texture in order to display to the screen. So I have my class looking like this:
      class Sprite { public: Sprite(Texture* texture); ~Sprite(); Texture* texture; //Other class stuff } Now in the current state of my Sprite class would I be correct in that I cannot use it as a member in a different class, because it has no no-arg (default) constructor? That the only way this class could be a member is if it was a pointer?
      class SpriteContainer { public: SpriteContainer(); ~SpriteContainer(); Sprite singleSprite; //**BAD** not allowed because Sprite has no no-arg (default) constructor Sprite* singleSpritePtr; //This is allowed because its a pointer std::vector<Sprite> sprites; //**BAD** not allowed because Sprite has no no-arg (default) constructor std::vector<Sprite*> spites; //This is allowed because its a vector of Sprite pointers } I guess my really problem here is that I struggle with when a variable/class should be a pointer or not
      2. How do you make an abstract class where there are no methods that should be pure virtual functions?
      All the functions of the base class have there implementation, but I also do not want this class to be instantiated
      //Should not be able to instantiate this class. Should be an Abstract class class BaseClass { public: BaseClass() { x = 0; }; virtual ~BaseClass() { }; int x; void coolMethod() { ++x; } } //Can instantiate this class. coolMethod can be called from this class class DerivedClass : public BaseClass { public: DerivedClass(); ~DerivedClass(); }  
      Questions about smart pointers:
      1. I have never used these before, but are smart pointers ok when working with COM objects?
      Will the smart pointer automatically call a COM object's Release function or should I wrap my COM object and explicitly call Release in the wrapper class' destructor?
      2. Lets say there is a case where I wanted to give back the user of some APIs a pointer to a resource, but I also want them to know that they don't have to worry about cleaning it up. EG There is resource loader that will clean up all loaded resources once the program shuts down. The user has to do/worry about nothing.
      What type of smart pointer should I use in a case like this? Should it be a Shared pointer? Or should I make the resource a Unique pointer and then return to the user a raw pointer?
    • By Kazuma506
      I am trying to recreate the combat system in the game Life is Feudal but make it more complex. The fighting system works by taking in the direction of the mouse movement and if you press the left click it will swing in that direction, though stab, overhead, left (up, down, left right) and right are the only swings that you can do. If you wanted to you could also hold the swing by holding left click so you are able to swing at the perfect moment in the battle. I want to change this so add in more swing directions but I also want to code this from scratch in Unreal. Can anyone give me any pointers or maybe a few snippets of code that work in Unreal that could help me start to implement this type of system?
       
       
    • By noodleBowl
      I was wondering if someone could explain this to me
      I'm working on using the windows WIC apis to load in textures for DirectX 11. I see that sometimes the WIC Pixel Formats do not directly match a DXGI Format that is used in DirectX. I see that in cases like this the original WIC Pixel Format is converted into a WIC Pixel Format that does directly match a DXGI Format. And doing this conversion is easy, but I do not understand the reason behind 2 of the WIC Pixel Formats that are converted based on Microsoft's guide
      I was wondering if someone could tell me why Microsoft's guide on this topic says that GUID_WICPixelFormat40bppCMYKAlpha should be converted into GUID_WICPixelFormat64bppRGBA and why GUID_WICPixelFormat80bppCMYKAlpha should be converted into GUID_WICPixelFormat64bppRGBA
      In one case I would think that: 
      GUID_WICPixelFormat40bppCMYKAlpha would convert to GUID_WICPixelFormat32bppRGBA and that GUID_WICPixelFormat80bppCMYKAlpha would convert to GUID_WICPixelFormat64bppRGBA, because the black channel (k) values would get readded / "swallowed" into into the CMY channels
      In the second case I would think that:
      GUID_WICPixelFormat40bppCMYKAlpha would convert to GUID_WICPixelFormat64bppRGBA and that GUID_WICPixelFormat80bppCMYKAlpha would convert to GUID_WICPixelFormat128bppRGBA, because the black channel (k) bits would get redistributed amongst the remaining 4 channels (CYMA) and those "new bits" added to those channels would fit in the GUID_WICPixelFormat64bppRGBA and GUID_WICPixelFormat128bppRGBA formats. But also seeing as there is no GUID_WICPixelFormat128bppRGBA format this case is kind of null and void
      I basically do not understand why Microsoft says GUID_WICPixelFormat40bppCMYKAlpha and GUID_WICPixelFormat80bppCMYKAlpha should convert to GUID_WICPixelFormat64bppRGBA in the end
       
  • Popular Now