-2

Can a WinAPI UUID be changed after its been assigned? Can a Linux uuid_t be changed after its been assigned?

For example (example relating to UUID but the same question for uuid_t):

class Component
{
public:
    UUID id; // considering whether to make this public or not

    Component()
    { 
        UuidCreate(&id);
    }
};

Component c;
UuidCreate(c.id); // can it be changed after already being assigned? Is it constant?
sazr
  • 24,984
  • 66
  • 194
  • 362
  • 1
    Since you haven't declared either `c` or `Component::id` as `const` they can be easily changed. – Ross Ridge Dec 28 '15 at 02:38
  • 1
    This sounds like an [XY problem](http://meta.stackexchange.com/q/66377/205381). Why do you need to know, whether a variable of a particular type can be modified after it was constructed? – IInspectable Dec 28 '15 at 02:42
  • Definitely an XY problem. You don't "change" UUID's. The only sensible modifying operation is assignment, which you'd need e.g. in `std::vector` to support `.erase` – MSalters Dec 28 '15 at 02:53
  • @RossRidge The purpose of the question; I dont want users of class Component to be able to change `UUID` at all (by subclassing or outside interaction). Now changing to `const UUID` throws a compile error when calling `UuidCreate()` (Cannot convert from const UUID* to UUID*) so this doesn't seem like a solution. – sazr Dec 28 '15 at 03:36
  • Please see [The Definitive C++ Book Guide and List](http://stackoverflow.com/q/388242/1889329). Access modifiers are explained in all introductory books. – IInspectable Dec 28 '15 at 11:28

1 Answers1

3

Yes, both UUID and uuid_t are just structs containing a series of integers. If any consumer can get a reference to it that isn't const, it will be able to modify it.

If you don't want consumers to change your UUID, the best approach is to make it a private member and only expose it to the outside world via an accessor that returns a const reference:

class Component
{
public:
    Component()
    { 
        UuidCreate(&id);
    }

    const UUID& GetId() const
    { 
        return id;
    }

private:
    UUID id;
};
Collin Dauphinee
  • 13,664
  • 1
  • 40
  • 71
  • 2
    The caller of `GetId()` can simply cast the `const` away and then modify the UUID directly since a reference to it is being returned. To avoid that, better to return the UUID by value instead of by reference, if at all. – Remy Lebeau Dec 28 '15 at 06:50
  • @RemyLebeau: C++ uses the philosophy of "protecting against Murphy, not Machiavelli". Your "solution" to return by value still doesn't protect against `reinterpret_cast(&theComponent)`. – MSalters Dec 28 '15 at 13:26