C ++ passes structure or object by value

I have it:

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 passed one of them to a method like this:

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

I was getting unpleasant crashes from this until I tried to override the method to take the link:

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

And now everything works.

But how can a value structure be screwed with memory?

+3
source share
4 answers

. , , , , , . , Configuration, . Configuration , " ".

. , , . std::string, , , . , , - - char.

+2

, strdup, , - , , . , , , , .

:

  • , , ,

  • , strdup - std:; , ctor op.

  • inline - .

+6

, units *name, *name. , , *name Configuration.

+1

struct a copy constructor char * name; (, โ€‹โ€‹ , ).

, char * . std::string, .

+1

Source: https://habr.com/ru/post/1757122/


All Articles