unique_ptr without move, why is this working? - c++11

During a code review I found that a C++ function expecting a unique_ptr gets passed the uniqe_ptr by std::move but neither does the function move the unique_ptr as return value nor assigns the caller the return unique_ptr back to it's unique_ptr, so I'd expect this would crash.
Example:
std::unique_ptr<X> fun(std::unique_ptr<X> p) {
// Do something with the unique_ptr p
return p;
}
At some other place, I found the following calls:
void someFunction() {
auto p = std::make_unique<X>();
//...
fun(std::move(p));
// Do something else
fun(std::move(p));
//...
}
So I'm wondering whether this code is OK or if it is just luck that it executes.
[EDIT]: Completed the example

In this fragment:
fun(std::move(p));
fun(std::move(p));
p is moved-from, which leaves it null. So the second time you call fun(), it receives a null pointer. Which is fine, so long as it does not dereference that pointer.

It looks to me like the intent was to call fun like this:
p = fun(std::move(p));
p = fun(std::move(p));
In which case ownership of p would be passed back-and-forth to and from the function. I would have preferred to make fun a void function and pass p in by reference or even as a raw X* type.

Related

Golang LinkedList remove first element

I'm trying to implement LinkedList operation in Golang from scratch. But I found a problem when dealing with removing first element. My approach is using OOP style, but it seems the first element is not removed. This is the code I write,
type LinkedList struct {
Value int
next *LinkedList
}
func (ll *LinkedList) Remove(index int) error {
pointer := ll
var pointerPrev *LinkedList = nil
current := 0
for current < index {
pointerPrev = pointer
pointer = pointer.next
current++
}
if pointer == ll {
ll = ll.next // this line is problematic
pointer = nil
} else {
if pointer.next == nil {
pointerPrev.next = nil
} else {
pointerPrev.next = pointer.next
pointer = nil
}
}
return nil
}
Any suggestion how I implement this way of removing without returning new LinkedList pointer?
Everything is passed as a copy, so you can only change something if a pointer to it is passed, and you modify the pointed value.
So you can't do what you want without having to return the new list head (which you have to assign at the caller).
An alternative could be to pass the address of the head pointer (type of **LinkedList), which is ugly (having to always pass the head pointer's address). You could also add a separate method for removing the first element, something like RemoveFirst(), so you only have to pass to this method only. This RemoveFirst() could return the new head too, which the caller has to assign. This RemoveFirst() could also be a "regular" function instead of a method.
Another alternative is to create a wrapper for the list, which holds a pointer to the head. And you implement methods on the wrapper, not on the node type. And a method of the wrapper could change the field holding the head pointer.
See related: Can the pointer in a struct pointer method be reassigned to another instance?

Is the unique_ptr returned from a function an lvalue?

Lately, I've been doing a little digging into the C++11 std and was playing around with unique_ptrs.
Let's say I have a function which returns a unique_ptr to an integer.
unique_ptr<int> GetUniquePtr(int i)
{
return make_unique<int>(i);
}
In my main function, I am able to take the address of the value returned by the function. This means that the expression must evaluate to an lvalue
int main()
{
cout << &(GetUniquePtr(5));
}
I know if I assign the function call to a unique pointer, the move consturctor of the unique_ptr will be called, treating the returned value as an rvalue reference.
int main()
{
unique_ptr<int> uPtr = GetUniquePtr(5);
}
This dual behaviour of returning unique_ptr kind of confuses me, as I was of the impression that unique_ptr returned from a function call is always evaluated as an rvalue.
Can anyone shed some light on what's actually going on?

C++11 Multiline lambdas can deduce intrinsic types?

I use C++11 lambdas quite a lot, and I've often run into compile errors on multiline lambdas because I forgot to add the return type, as is expected, but I recently ran into one example that doesn't have this issue. It looks something like this:
auto testLambda = [](bool arg1, bool arg2)
{
if (arg1)
{
if (!arg2)
{
return false;
}
return true;
}
return false;
};
This compiles just fine even though there's no return type specified. Is this just Visual Studio being dumb and allowing something it shouldn't, or can lambdas just always deduce intrinsic types?
I tried this with return values of all ints or floating point values and it also compiled just fine. I just found this to be really surprising so I wanted to be absolutely sure how it works before I start making assumptions and omitting return types that might break later on.
Lambdas follow the same template deduction rules as auto-returning functions:
Template argument deduction is used in declarations of functions, when deducing the meaning of the auto specifier in the function's return type, from the return statement.
For auto-returning functions, the parameter P is obtained as follows: in T, the declared return type of the function that includes auto, every occurrence of auto is replaced with an imaginary type template parameter U. The argument A is the expression of the return statement, and if the return statement has no operand, A is void(). After deduction of U from P and A following the rules described above, the deduced U is substituted into T to get the actual return type:
auto f() { return 42; } // P = auto, A = 42:
// deduced U = int, the return type of f is int
If such function has multiple return statements, the deduction is performed for each return statement. All the resulting types must be the same and become the actual return type.
If such function has no return statement, A is void() when deducing.
Note: the meaning of decltype(auto) placeholder in variable and function declarations does not use template argument deduction.

Understanding enum and function signature

In learning Swift, I came across this code: -
enum ServerResponse {
case Result(String, String)
case Error(String)
}
for i in 1...10{
let mySuccess: ServerResponse = {
let zeroOrOne = rand() % 2
if zeroOrOne == 0 {
return ServerResponse.Result("7:00 am", "8.09 pm")
} else {
return ServerResponse.Error("Out of cheese.")
}
}()
var serverResponse: String
switch mySuccess {
case let .Result(sunrise, sunset):
serverResponse = "Sunrise is at \(sunrise) and sunset as \(sunset)"
case let .Error(error):
serverResponse = "Failure... \(error)"
}
println(serverResponse)
}
As can be seen here, there are parentheses () after the closing end brace of the declaration for:
let mySuccess: ServerResponse = {
...
}()
Without the parenthesis, playground produces the error:-
Function produces expected type 'ServerResponse'; did you mean to call it with ()?
Considering a function has the signature: -
func name(param) -> returnType
Can someone please explain why the parenthesis are required here? Is it a form of minimised closure, or something else?
It's an anonymous function/lambda/closure (however you want to call it exactly), taking no argument, and whose return type is inferred by the compiler, which is then called immediately. It's similar to (function() {…})() in JavaScript.
It has the big advantage of allowing you to define mySuccess as a constant instead of a variable. Additionally, it creates a scope, such that intermediary variables (like zeroOrOne) are not visible outside.
What I'm wondering is just why the author of this code didn't use the same style to define and assign serverResponse…
Your ServerResponse is not a function, it is an enum, but without the parentheses the block you would be trying to assign to mySuccess IS a function (that returns a ServerResponse), and therefore cannot be assigned to a ServerResponse. The result of calling the function (adding the parentheses) can be.

Functor and function pointer logic

class StrangeFunctor
{
public:
StrangeFunctor(int (*comp)(string, string))
{
this->comp = comp;
}
int operator()(string str1, string str2)
{
return –comp(str1, str2);
}
private:
int (*comp)(string, string);
}
I was just curious as what the above code actually did. Assuming the functor was properly initialized and given to a sorting function for comparison purpose, my hunch is that it reverses the order of the passed argument, but I'm not sure if that is correct and why the would be correct.
This functor takes in a function pointer and then flips the sign on that method's return value.
return –comp(str1, str2);
If used with sorting like you said, it would invert the order of what was being sorted, given by the original function pointer.

Resources