The code at this GitHub file uses a C++ variable "declaration" syntax I'm not familiar with:
std::unique_ptr<CRecentFileList> {m_pRecentFileList} = std::make_unique<CRecentFileList>(...
(m_pRecentFileList
is declarared in a superclass.)
What does it mean when you wrap a variable declaration in braces? (not an initializer list)
I extracted a minimal test case which compiles:
class foo {
int* p;
void f(){
std::unique_ptr<int> {p} = std::make_unique<int>(1);
}
};
Changing int* p
to std::unique_ptr<int> p
creates a compilation error due to unique_ptr(const unique_ptr&) = delete;
This makes me think braced declaration assigns to a outer-scope variable with the same name. I tried creating a test program, but it fails to compile:
int main(){
int x;
int {x} = 1;
}
error: using temporary as lvalue [-fpermissive]
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);
.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With