C++11- Use nullptr all the time? - pointers

I'm just a little bit confused.
When should I use nullptr?
I've read on some sites that it should always be used, but I can't set nullptr for a non-pointer for example:
int myVar = nullptr; // Not a pointer ofcourse
Should I always use NULL non-pointers and nullptr for pointers?
Thanks to any help! I'm very new to c++ 11 (and c++ overall).

Always use nullptr when initializing pointers to a null pointer value, that's what it is meant for according to draft n3485.
[lex.nullptr] paragraph 1
The pointer literal is the keyword nullptr. It is a prvalue of type
std::nullptr_t. [ Note: std::nullptr_t is a distinct type that is
neither a pointer type nor a pointer to member type; rather, a prvalue
of this type is a null pointer constant and can be converted to a
null pointer value or null member pointer value. [...] — end note ]
Now onto the use of NULL.
According to the same draft it shall be defined as follows.
[diff.null] paragraph 1
The macro NULL, [...] is an
implementation-defined C ++ null pointer constant in this
International Standard.
and null pointer constant as follows.
[conv.ptr] paragraph 1
A null pointer constant is an integral constant expression [...]
prvalue of integer type that evaluates to zero or a prvalue of type
std::nullptr_t.
That is, it is implementation-defined behavior whether NULL is defined as an integer prvalue evaluating to zero, or a prvalue of type std::nullptr_t. If the given implementation of the standard library chooses the former, then NULL can be assigned to integer types and it's guaranteed it will be set to zero, but if the later is chosen, then the compiler is allowed to issue an error and declare the program ill-formed.
In other words, although conditionally valid [read IB], initializing an integer using NULL is most probably a bad idea, just use 0 instead.
On the other hand, according to the above NULL is guaranteed to initialize pointers to a null pointer value, much like nullptr does, but while NULL is a macro, what accompanies several caveats, nullptr is prvalue of a specific type, for which type checking and conversion rules apply. That's mostly why nullptr should be prefered.

consider the two function overloads:
void foo(int)
void foo(int*)
in C++, people tend to use 0 as a null value. Other people use NULL. (NULL is really just a fancy macro for 0)
If you call foo(0) or foo(NULL), it becomes ambiguous which one should be called. foo(nullptr) clears up this ambiguity, and will always call foo(int*).

Related

Why is `std::ptr::null` not usable with unsized types?

As I understand, the standard (only?) way to make a null pointer in Rust is std::ptr::null.
However, that function is declared as follows.
pub const fn null<T>() -> *const T
In this declaration, T is implicitly assumed to have fixed size (otherwise, it would be T: ?Sized). As a consequence, it is impossible to use this function with *const str or *const [u32] for example. test it in the playground
Is there a good reason for excluding unsized types? What's wrong with wanting to create a null *const str?
A pointer to an unsized type is a fat pointer with two components: the pointer and the type metadata (a length for slices, and a vtable pointer for trait objects; in the future, Rust may allow other kinds of metadata). null only implies a value for the pointer part; there's no obvious choice for the other value. (You might think 0 is obvious for the length of a null slice pointer, and I can see the argument, but if the pointer is null it hardly matters how many things are there; you can't dereference it anyway, so making the size 0 is not necessary to ensure safety.)
There is no way to create a null pointer to a trait object, but as of Rust 1.42, you can use ptr::slice_from_raw_parts to create a null pointer to a slice. Let's suppose the length of the slice is 0:
use std::ptr;
fn main() {
let p: *const [u32] = ptr::slice_from_raw_parts(ptr::null(), 0);
println!("{:?}", p);
}
There is no equivalent function for str, but you could make one by creating a null *const [u8] and casting it with as.
This function (or the related slice_from_raw_parts_mut) is the only way to soundly create a null pointer to a slice. The usual way to get a raw pointer is by casting a reference, but references may never be null.

Pointer methods on non pointer types

According to this response to this question
The rule about pointers vs. values for receivers is that value methods can be invoked on pointers and values, but pointer methods can only be invoked on pointers
But in fact I can execute pointer method on non pointer values:
package main
import "fmt"
type car struct {
wheels int
}
func (c *car) fourWheels() {
c.wheels = 4
}
func main() {
var c = car{}
fmt.Println("Wheels:", c.wheels)
c.fourWheels()
// Here i can execute pointer method on non pointer value
fmt.Println("Wheels:", c.wheels)
}
So, what is wrong here? Is this a new feature ? or the response to the question is wrong ?
You are calling a "pointer method" on a pointer value. In the expression:
c.fourWheels()
c is of type car (non-pointer); since the car.fourWheels() method has a pointer receiver and because the receiver value is a non-pointer and is addressable, it is a shorthand for:
(&c).fourWheels()
This is in Spec: Calls:
If x is addressable and &x's method set contains m, x.m() is shorthand for (&x).m().
The statement:
The rule about pointers vs. values for receivers is that value methods can be invoked on pointers and values, but pointer methods can only be invoked on pointers
Interpret it like this:
If you have a value method, you can always call it: if you have a value, it's ready to be the receiver; and if you have a pointer, you can always dereference it to obtain a value ready to be the receiver.
If you have a pointer method, you may not always be able to call it if you only have a value, as there are several expressions (whose result) are not addressable, and therefore you would not be able to obtain a pointer to it that would be used as the receiver; such examples are function return values and map indexing expressions. For details and examples, see How can I store reference to the result of an operation in Go?; and How to get the pointer of return value from function call? (Sure, you could always assign it to a local variable and take its address, but that's a copy and the pointer method could only modify this copy and not the original.)

Confused with implicit pointer dereference when assigning a pointer to interface in Go

I am new to Go, and I am studying its interface feature.
Here is the code:
package main
import (
"fmt"
"reflect"
)
type Integer int
func (a Integer) Less(b Integer) bool {
return a < b
}
func (a *Integer) Add(b Integer) {
*a += b
}
type LessAdder interface {
Less(b Integer) bool
Add(b Integer)
}
var a Integer = 1
var b LessAdder = &a
func main() {
fmt.Println(reflect.TypeOf(b))
fmt.Println(b.Less(2))
b.Add(a)
fmt.Println(a)
}
And it will output the the following:
*main.Integer
true
2
Well, this works pretty well.
The Point is:
How var b LessAdder = &a works. Does the pointer auto-dereference happens right here, or when b invokes member method?
The output *main.Integer tells us that b is a pointer to type Integer, hence it is the second case.
Then the tricky thing comes:
when I add fmt.Pringln(*b) to the code, the compiler comes with an error:
demo/demo1
./demo1.go:31: invalid indirect of b (type LessAdder)
And it confuses me. Since b is a pointer type to Integer, then dereferencing it should work. But why not?
Your last sentence:
"Since b is a pointer type to Integer, then dereferencing it should work."
Stop right there. b is not a variable of pointer type and therefore you can't dereference it.
It is a variable of interface type which is schematically a pair of a value and a type (value,type), holding &a as the value and *Integer as the type (blog article The Laws of Reflection, section The representation of an interface).
This is a declaration of a variable of pointer type, *Integer:
var ip *Integer
And this is one of an interface type:
var intf LessAdder
When you do this:
var b LessAdder = &a
What happens is that an interface value (of type LessAdder) is created automatically/implicitly which will hold the value &a (and the type *Integer). This is a valid operation because the type of &a (which is *Integer) implements the interface LessAdder: the method set of *Integer is a superset of the interface LessAdder (in this case they are equal, the method set of an interface type is its interface).
Now when you call b.Less(2), since Less() has a value receiver, the pointer will be dereferenced and a copy of the pointed value will be made and used/passed as the value receiver of the method Less().
fmt.Println(reflect.TypeOf(b)) doesn't lie, but it will print the dynamic type of b. The dynamic type of b is indeed *Integer, but the static type of b is LessAdder and the static type is what determines what you can do with a value and what operators or methods are allowed on it.
LessAdder is declared as an interface with the methods Less and Add. Since Add is declared with a receiver of *Integer, a *Integer can be a LessAdder; an Integer can't. When you do var b LessAdder = &a, it's the pointer to a that's stored in the interface b.
The automatic indirection occurs at the call to b.Less(2), because both methods on *Integer and methods on Integer contribute to the method set of *Integer.
You can't use *b because although b contains a *Integer, statically its type is LessAdder, not *Integer. Leaving aside the representation of interfaces, LessAdder isn't a pointer type, and *b, if it was allowed, would have no expressible type at all.
You can use a type assertion to access b as an Integer * again; b.(*Integer) is an expression of type *Integer, and *b.(*Integer) is an Integer. Both of these will run-time panic if the value in b is not a *Integer after all.

Intentional Comparison Between Pointer & Integer in C

Will the GCC Compiler correctly handle the following?
uint32 fn(uint32 adr, uint8 *ptr) {
return (ptr==adr);
}
In other words will it auto cast ptr to an integer that stores the memory address pointed to?
Yes, GCC will handle it correctly -- by diagnosing the error in your code.
C has no implicit conversions between integer types and pointer types (other than the special case of an integer constant 0 being treated as a null pointer constant), and == cannot compare values of integer and pointer type.
To correct the error, add a cast (an explicit conversion) to convert adr to type uint8*:
return ptr == (uint8*)adr;
or, even better, make the two parameters of the same type in the first place:
uint32 fn(uint8 *adr, uint8 *ptr) {
return ptr == adr;
}
Unless you have some specific reason that adr needs to be an integer rather than a pointer, but you haven't told us what that reason might be.
C is more strongly typed that a lot of people assume it is.

How can I access variables in vector<struct> *obj?

How would I get my variables out of a vector?
I can't use the binary insertion operators or the equal operators.
Earlier, I declared a vector<someStruct> *vObj and allocated it, then returned the vObj
and called it in this function:
vector<sameStruct> firstFunc();
for (unsigned int x = 0; x < v->size(); x++)
{
v[x];
}
when I debug it, v[x] now has the full contents of the original vector, as it did before without the subscript/index.
But I don't think I've done anything to progress beyond that.
I just have about 4 variables inside my vector; when I debug it, it has the information that I need, but I can't get to it.
As it is written v is a pointer to a vector of structs.
When you index directly into v all you are doing is pointer arithmatic. v[x] is the vector of structs at position x (assuming that v is an array if it is just a single object at the end of the pointer then v[x] for x>0 is just garbage). This is because it is applying the [x] not to the vector pointed to by v but to the pointer v itself.
You need to dereference the pointer and then index into the vector using something like:
(*v)[x];
At this point you have a reference to the object at the xth position of the vector to get at its member functions / variables use:
(*v)[x].variable;
or
(*v)[x].memberfunction(parameters);
If you do not want to dereference the vector then access the element within it you might try something like:
v->at(x);
v->at(x).variable;
v->at(x).memberfunction;
This way you are accessing a member function of an object in exactly the same manner as when you called:
v->size();
I hope that this helps.
To use the [] operator to access elements you must do so on object, not a pointer to an object.
Try;
(*vec)[x];
E.g.
for (int i = 0; i < vec->size(); i++)
{
printf("Value at %d is %d\n", i, (*vec)[i]);
}
Note that when calling functions on a pointer you usually use the -> operator instead of the . operator, but you could easily do (*vec).some_func(); instead.
Operators such as [], --, ++ and so on can act both on objects and pointers. With objects they act as function calls, but on pointers they act as mathematical operations on the address.
For example;
pointer[nth];
*(pointer + nth);
Have exactly the same effect - they return the nth object from the start of the pointer. (note the location of the * in the second example, it's called after the offset is applied.
Two other tips;
You can also avoid the need to dereference like this by passing the vector as a reference, not a pointer. It's not always a suitable option but it does lead to cleaner code.
void my_func(std::vector<int>& vector)
{
// vector can then be used as a regular variable
}
If you're going to be passing vectors of a specific type to functions a lot then you can use a typedef both for clarity and to save on typing.
typedef std::vector<int> IntVector;
void my_func(IntVector& vector)
{
}

Resources