Common C++ Gotchas
vickychijwani.me
vickychijwani.me
#6 sometimes you actually will want an A(A&) constructor... for example, if you have constructor overloaded with a greedy template argument.
#8 objects returned by value will also bind to an rvalue reference
#9 Remember in C++11 there's also new T{};
#10 isn't absolutely correct either, dynamic_cast can actually be used in some circumstances where static_cast or implicit casting could have been used.
struct A {
};
struct B: A {
};
int main() {
auto b = new B();
auto a = dynamic_cast<A*>(b); // fine
}There are reasons why you might want to use public inheritance that have nothing to do with run-time polymorphism.
Slicing isn't even necessarily harmful either... but I'm not sure what you had in mind.
It seems like, if you're not providing a virtual destructor, you force users into delegation rather than inheritance, and that will catch some % of developers who aren't on the ball. They'll have leaks...
As far as i know (old info) there's no such thing as a "final" class, so anybody can inherit even if you don't want them to.
Anyone can technically publicly inherit from a value class, but if they do it's absolutely their fault :)
You have the `final` specifier since C++11 to state a class cannot be inherited from, but this notion of "You really shouldn't inherit from this class." has been around since classical object orientation has, C++ just couldn't express it as a language.
So if your class currently isn't being inherited from, make your public dtor nonvirtual. If and when it needs to be a base class, then the author can modify your class to have a virtual dtor, or use composition (which is often the superior alternative). If source code is not available, then composition it is. I would advise against making it virtual "just in case", that's premature pessimisation.
You mean per-object vtable pointer? Or per-type vtable?
struct A {
A (A const&); // copy constructor;
A (A&&); // move constructor
template <typename T> A (T&&); // template constructor
};
int main() {
A a1;
A a2(a1); // calls the template constructor because a1 is an lvalue
}Smart pointers are not a panacea.
You don't always have control over the code you are writing, an example that comes to my mind quickly is ffmpeg.
You're exactly right. But there are multiple complications:
- unique_ptr and shared_ptr are only available in C++11 onwards, we're still to migrate to a new compiler
- auto_ptr is a joke [1]
- I've got to live with `delete` in our gargantuan codebase at work
- I could (and should) use boost's smart pointers, and indeed I do when possible. But I admit I sometimes even forget to use those and end up with naked pointers instead.
And if you really can't, and you need a container that automatically frees its contents when destroyed, just stick it in a STL vector.
std::unique_ptr (or its predecessor, boost:scoped_ptr if you don't have access to C++11) should be used all over the place. There are many reasons why you may not want by-value containment of objects, and std::unique_ptr gives you object-lifetime ownership of pointers.
I'm interested in reading them actually, would you mind listing them?
Polymorphism - a value object is always exactly its static type, but you can substitute in different derived types for a unique_ptr. The previously-held object is automatically destroyed when you do this. This is essential for the State and Strategy patterns.
Reassignment/swap - reassigning a unique_ptr destroys its previous value and transfers ownership of the new one. Reassigning a value object invokes operator=. The former can (sometimes, not always) be faster than the latter - think about cases where you just want a quick pointer swap inside the object, rather than having to shuffle all the bits in a large struct around.
Release - unique_ptr has a member function to release ownership of the object, while this concept doesn't apply to value objects. Where might this be useful? Well, imagine trying to achieve exception safety inside a factory function with complex construction logic, and then transferring ownership to the caller. It's common to immediately assign the new object to a unique_ptr upon construction (so if an exception is ever thrown, it is destroyed properly), perform your logic, and then return ptr.release().
#include <iostream>
#include <memory>
std::unique_ptr<int> foo() {
std::unique_ptr<int> x(new int(42));
return x;
}
int main() {
std::cout << *foo();
}
the folllowing also works: std::unique_ptr<int> foo(std::unique_ptr<int> x) {
return x;
}
the following however will not work because RVO cannot be employed (the space occupied on the stack for the return value can't be shared with the source object) std::unique_ptr<int> foo(bool b) {
std::unique_ptr<int> x(new int(42));
std::unique_ptr<int> y(new int(17));
return b ? x : y;
}You could imagine another example where the goal of the factory function is to construct an object and then set one of two or more other owned pointers to the value. You still want something to hold ownership of the pointer, but don't know its eventual home until after some complicated logic finishes, and don't want to pay the copy constructor cost. That might make a better illustration (or technically, you'd use operator= instead of release(), but same basic point).
> Nullability
What do you think of boost::optional?
> Polymorphism
unique_ptr is probably the wrong choice here. You should be using ptr_vector: http://stackoverflow.com/questions/9469968
> Reassignment/swap
The indirection and heap (de)allocation also imposes a slowdown, though. Have you actually experienced this to be worth it in some cases, or is this just a guess?
> Release
I don't think this is a valid reason...? This is a pretty common idiom for releasing value types:
Type().swap(existing); // release 'existing'
But aesthetically, I've learned to distrust any code that likes to throw objects around the design by pointer. It's untidy, and leads to needless abstraction and poor coupling. The time you spend trying to fit your objects into by-value composition is time you save later not having to untangle your knots of pointers.
The whole notion of having to carefully manage ownership via syntax (seriously: try explaining to a python programmer why they have to use this insane "unique" thing just to store a reference to something) instead of via structure (put the object inside its owner) is just vile, aesthetically. And it's something that C++ nuts tend to be really bad about.
http://clhs.lisp.se/Issues/iss152_w.htm
"The ambiguity at issue arises for the case where there are transfers of control from the cleanup clauses of an UNWIND-PROTECT. ..."
It is not clear what exit points are visible when the cleanup-forms (morally similar to C++ destructor calls) are invoked. Are the exit points that are skipped torn down all the way to the control transfer's target, or is the tear-down interleaved with the unwinding.
You might need to do this if you're implementing your own smart handle or writing a factory function for a class with a private constructor (make_unique will not work).
Off the top of my head, I can't think of any good reasons to use delete.
> If you'll tolerate my hypocrisy for a moment, here's my suggestion: try to avoid putting the const at the beginning like that
Or you could not do that, and put const in the least ambiguous place, and since you rarely have a 'type* const ' it works very well just using:
const type*
for pointers to const types, and type* const
for const pointers to types, and entirely unambiguous.Shouldn't rvalue move semantics kick in and prevent the copy?
Remember this rule and the throws behavior makes perfect sense, as do a lot of other C++ gotchas.