What do braces on the left-hand side of a variable declaration mean, such as in T {x} = y?

It’s not a declaration. It’s an assignment to a temporary.

In std::unique_ptr<int> {p} = std::make_unique<int>(1);, std::unique_ptr<int> {p} creates a unique_ptr temporary that takes ownership of the object p points to, then std::make_unique<int>(1) is assigned to that temporary, which causes the object p points to to be deleted and the temporary to take ownership of the int created by the make_unique; finally, at the ;, the temporary itself is destroyed, deleting the make_unique-created int.

The net result is delete p plus a useless new/delete cycle.

(It would be a declaration had it used parentheses rather than braces:
std::unique_ptr<int> (p) = std::make_unique<int>(1); is exactly equivalent to std::unique_ptr<int> p = std::make_unique<int>(1);.)

Leave a Comment

tech