Re: unique_ptr and rvalue question
On 29 Mrz., 08:47, Brendan <catph...@catphive.net> wrote:
I have a unique_ptr type:
typedef std::unique_ptr<int, void(*)(int*)> unique_fd;
In a function that returned unique_fd I use it like this:
unique_fd u_sock = make_unique_fd(sock);
if (bind(*u_sock, cur_addr->ai_addr, cur_addr->ai_addrlen) == 0)
return u_sock;
GCC 4.4 compiles this without errror... However, shouldn't it require
return std::move(u_sock)?
No, this is not necessary, see below.
Are all locals considered r values in a return statement, which would
kind of make sense, or is this a bug in GCC's standard library?
That comes quite near. It's part of the famous copy-optimization
paragraph (12.8 [class.copy]/19 in N3035) starting with:
"When certain criteria are met, an implementation is allowed to omit
the copy construction of a class object [..]"
Now this rule already exists in C++03, but has been extended in
C++1x to cope with move constructors in p. 20:
"When the criteria for elision of a copy operation are met and the
object to be copied is designated by an lvalue, overload resolution
to select the constructor for the copy is first performed as if the
object were designated by an rvalue. If overload resolution fails, or
if the type of the first parameter of the selected constructor is not
an rvalue reference to the object?s type (possibly cv-qualified),
overload resolution is performed again, considering the object as
an lvalue. [ Note: This two-stage overload resolution must be
performed regardless of whether copy elision will occur. It
determines the constructor to be called if elision is not performed,
and the selected constructor must be accessible even if the call
is elided. ?end note ]"
Additionally a code example is provided:
class Thing {
public:
Thing();
~Thing();
Thing(Thing&&);
private:
Thing(const Thing&);
};
Thing f(bool b) {
Thing t;
if (b)
throw t; // OK: Thing(Thing&&) used (or elided) to throw t
return t; // OK: Thing(Thing&&) used (or elided) to return t
}
Thing t2 = f(false); // OK: Thing(Thing&&) used (or elided) to
construct of t2
In fact std::unique_ptr is quite similar to Thing above.
Standard refs?
See 12.8 [class.copy]/19+20 in the working draft N3035.
HTH & Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]