Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ passing struct or object by value

I have this:

enum Units { Pounds, Kilos };

struct Configuration
{
    const Units units;
    const char *name;

    inline Configuration(Units pUnits, char *pName) : units(pUnits)
    {
        name = strdup(pName);
    }

    inline ~Configuration() { free((void *)name); }
};

I was passing one of these to a method like this:

Configuration cc(Kilos, "abc");
cdao->write(cc);

I was getting nasty crashes from this until I tried redefining the method to take a reference:

Configuration cc(Kilos, "abc");
cdao->write(&cc);

And now everything works.

But how could the struct by value be screwing with memory?

like image 937
Germán Avatar asked Mar 23 '26 10:03

Germán


1 Answers

The fact that you are using strdup indicates that there is something wrong with your code, and the wrong thing is you don't have a copy constructor. Any time you have a destructor, you almost certainly also need a copy constructor, which will copy the object correctly when you call by value.

To improve your code:

  • create a copy constructor and probably an assignment operator which allocate and copy the string correctly

  • better yet, get rid of strdup - use a std:;string, in which case you won't need a destructor, copy ctor or assignment op.

  • get rid of the "inline" keywords - they are doing nothing.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!