thể trùng lặp:
Returning unique_ptr from functionsTại sao tôi được phép sao chép unique_ptr?
20.7.1.2 [unique.ptr.single] định nghĩa constructor sao chép như thế này:
// disable copy from lvalue
unique_ptr(const unique_ptr&) = delete;
unique_ptr& operator=(const unique_ptr&) = delete;
Vì vậy, tại sao các biên dịch đoạn mã sau khỏe?
#include <memory>
#include <iostream>
std::unique_ptr<int> bar()
{
std::unique_ptr<int> p(new int(4));
return p;
}
int main()
{
auto p = bar();
std::cout<<*p<<std::endl;
}
tôi biên soạn nó như thế này:
g++ -O3 -Wall -Wextra -pedantic -std=c++0x kel.cpp
Trình biên dịch: g ++ phiên bản 4.6.1 20.110.908 (Red Hat 4.6.1-9)
+1 để thực sự cho chúng tôi biết bạn đang sử dụng trình biên dịch nào và cách bạn biên dịch mã. Một cảnh hiếm hoi trên StackOverflow. –
Xem http://stackoverflow.com/questions/4316727/returning-unique-ptr-from-functions – Sjoerd