I'm learning about copy constructors; originally started with trying to understand why I got a "use of deleted function" error when I had a unique_ptr
as an argument in a class' constructor. That led me to learn that unique_ptr
s are intentionally not copyable.
But then why does the following not violate non-copyability of unique_ptr
s? Function foo()
returns a unique_ptr
- so a copy is placed on the stack then assigned to variable p
. I'm not following something here, because this looks like the copy constructor should be invoked.
// main.cpp
#include <memory>
#include <iostream>
std::unique_ptr<int> foo() {
return std::unique_ptr<int>(new int( 42 ));
}
int main( int argc, char* argv[] ) {
std::unique_ptr<int> p = foo();
std::cout << *p << std::endl;
return 0;
}
$ g++ --version && g++ -g ./main.cpp && ./a.out
g++ (Debian 6.3.0-18+deb9u1) 6.3.0 20170516
Copyright (C) 2016 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
42
Aucun commentaire:
Enregistrer un commentaire