202 points · by pabs3 · 5y ago · 295 comments
> The second one is there since this is C++, priority() might raise an exception, meaning that new Widget will be called, but never passed to std::shared_ptr, and thus never deleted!
Is now impossible (thank God!). See a full SO discussion here[1]. Stuff like this makes me so happy I don't write C++ anymore, but the gist of it is (from the standard):
> For each function invocation F, for every evaluation A that occurs within F and every evaluation B that does not occur within F but is evaluated on the same thread and as part of the same signal handler (if any), either A is sequenced before B or B is sequenced before A.
[1] https://stackoverflow.com/questions/38501587/what-are-the-ev...
f(**x, g());
The number of stars evaluated before 'g()' (0, 1 or 2) varies between compilers, and the program I was working on would break if only one * was evaluated before g.Another favorite “criticism” I have of C++ goes along the lines of “but someone could overload operator+ to be division!” I have only seen that as a contrived critic’s example, or a joke.
Actually, that’s what you are supposed to do, as this is the only way for a constructor to let the caller know that something went wrong.
Yeah there's definitely criticisms you can throw at C++, but this always struck me as stupid. You could also write an `add` method that divides in Java.
I've never liked the idea of 'operators' in the first place, tbh. Scheme opened my eyes in that they're all just procedures. And then with Smalltalk and Scala I saw that they can all just be methods as well.
I don't see how that is so. C++ 17 allows new Widget to complete and then the priority() call to execute and throw before both are passed to shared_ptr(), thus creating a leak. Your cited example [1] doesn't leak because both arguments are shared_ptr. Seems to me that C++ 17 does indeed solve this latter case but not the former.
> evaluations of A and B are indeterminately sequenced: they may be performed in any order but may not overlap: either A will be complete before B, or B will be complete before A. The order may be the opposite the next time the same expression is evaluated.
And:
> 21) Every expression in a comma-separated list of expressions in a parenthesized initializer is evaluated as if for a function call (indeterminately-sequenced)
Emphasis mine. What the above basically says is that in the case of some function `f(A, B)`, the arguments `A`, and `B`, are what's known as "indeterminately-sequenced" -- this mean that their execution cannot be interleaved (overlap) -- but they still individually execute in a non-deterministic order (A before B, and sometimes B before A)!
With that said, the good news is that B can now never throw in the middle of A, which is precisely what we have in OP's example.
priority() is not passed to shared_ptr(), only to processWidget().
processWidget(new Widget, priority());
I think I saw the above code elsewhere.
However in the Effective C++ example, the `shared_ptr` constructor gave a false sense of security as it seemed the `new`-ed `Widget` was always managed by the smart pointer from its allocation.
Another example is when undefined behavior occurs, like (iirc) signed integer overflow. Compilers can technically do anything they want, including weird things. But how often does that actually happen?
int a;
...
int b = a
if (a + 1 > b){
foo();
}
Then compilers will use the fact that integer overflow is undefined behavior. This allows the compiler to assume the `if` statement will always be true. And hence it removes this check.This isn't just the compiler removing a check the programmer wanted. This could occur because of constants, where other constants make the check meaningful. It could also occur after in-lining a specific function call.
Really, the only case where this optimization would be bad is if the author was trying to detect overflow. Sadly, detecting if something would cause undefined behavior in C code is hard. Because you cannot try the thing.
Turning optimizations on doesn't suddenly undefine any behavior, it just changes what the compiler does when encountering some of those behaviors (among other, non-UB based optimizations). A non-optimizing compiler and an optimizing compiler both have to conform to the standard.
As for paranoia about undefined behavior? Compilers won't emit a program to call you a pizza or format your disk. There are risks, but those aren't real ones.
how is that different from undefined?
It certainly is the case that most compiler writers have decided this is okay. And I personally tend to agree with them.
There's lots of cases where the object itself is big, though. Think of objects with big fixed arrays, "god objects" with a bajillion pointers, or objects which themselves allocate data in-line.
That's why there's also a std::make_unique even though it doesn't have a control block (although it was added later, but that was just an oversight).
I believe this is correct. Here's [0] some old Boost documentation on Boost's make_shared which inspired the C++ standard's make_shared. It mentions both reasons.
[0] https://www.boost.org/doc/libs/1_67_0/libs/smart_ptr/doc/htm...
If you want to get a pointer from something, you would write this:
auto fooPtr = mywidget.getPtr();
fooPtr->doCoolStuff();
But we all know references are better than pointers right? So we should just write... auto fooRef = myWidget.getRef();
fooRef.doCoolStuff()
The problem is... this is valid and will probably not do what you want. It will make a copy. What you want is actually auto& fooRef = myWidget.getRef();
I once spent an entire day debugging a bizarre crash because of that. I was asking for a reference to a scene graph, and what was actually happening is I was getting a clone of the scene graph (which was an object that couldn't be safely copied), and then destroying a bunch of shared pointers when the function returned. Fun times.> It is fundamental tenet of C's philosophy that the programmer is always right, even when they are wrong.
> by not deleting
I think there's a problem here.
C++ fails at this pretty spectacularly.
There is a problem indeed, which is OP's failure to implement exception-safe code.
If someone opts to use exceptions, they have the responsibility of writing their code in a way that complies with scenarios involving throwing exceptions.
Failing to support a scenario by not following the most basic principles is something that's on the person writing the code, not the language.
It would make as much sense to blame java for the problems you create by not initializing objects in some code paths, because your code started to throw null pointer exceptions.
I mean in hindsight it's obvious, but still not exactly what I wanted to happen.
For reference, what I did does actually work, temporarily.
In standard terminology, this is described as "invalidating iterators". There are a bunch of member functions in std::vector that either do or don't invalidate iterators, e.g. push_back(...) does but size() doesn't. And as the name implies, if you call a function that invalidates iterators, all your existing iterators/pointers/references become invalid.
It's not as much as "feeling free" as it is having to reallocate the array because you added elements beyond it's capacity and they had to be stored somewhere.
vector<int> v = {42};
...
auto x = v[0]
v.clear();
// if x was deduced as reference, using x at this point
// would be UB
std::cout<< x;But vector is usually what one should reach for unless one has a good reason not to. The only danger really comes when the lifetime of iterators and the thing they point to become a bit decoupled, even due to insertion!
In both Visual Studio and CLion, these types of features work well, in addition to plenty of more advanced features like address/thread sanitizers, fuzz testing, etc.
That variant has issues if getRef() actually returns a temporary object. You may want auto&&.
You can use decltype(auto) to preserve the actual type of the rhs.
[1] as discussed elsewhere initializer lists behave differently, but initializer_list itself was a mistake to start with.
So, yes, backward compatibility and historical baggage.
Note that if you use explicit wrappers for all object-owning pointers you would get either the right behavior or a compilation error.
int x; auto y = x;
do you expect y to be a reference? Surely not.
No, my friend, auto is for values, not references. You want a reference - you have to say so.
(And same goes for rvalue references - auto&& .)
I tend to think of pointer a as a general type aspect whereas reference is specifically on the variable that it's on and doesn't transfer. Sort or like how auto doesn't copy the static specifier.
Also the rules for auto are the same as for template argument deduction.
template<typename T>
std::vector<T> MakeVec(T val) {
std::vector<T> vec;
vec.push_back(val);
return vec;
}
int main()
{
int x = 1;
int& y = x;
std::vector<int> vec = MakeVec(y);
}
Notice how in this case MakeVec(y) makes a std::vector<int> not a std::vector<int&>. If you want your template argument function to take a reference, use T& not T (or use T&& which is a whole new complication). Similarly use auto& not auto.If you write C++ it might be obvious what the problem is.
If you don't, this will absolutely ruin your entire day.
The worst part is, 95% of the time, it will probably work without issue.
But eventually, pushing a new item to the Vector will trigger a relocation of the whole vector, which will invalidate your reference and bring down production. Have fun debugging that.
It does. Some collections have a "collection.retain" method.
collection.retain(|v| true_if_we_want_to_keep(v))
which goes through the collection in linear time and deletes any items for which the test is false. This is O(N).Some collections ("multi_map", which isn't used much, comes to mind) don't have that. You have to make a read pass over the collection, construct a list of things to delete, then go through the delete list and delete those items. Can't read and change with the same iterator. That's slower. But sound.
I'm OK with that. It avoids subtle bugs.
struct OrderedSet {
deque<string> storage;
set<string_view> vals;
}
The deque holds the string contents, and the set holds views of those contents. This is safe because the deque has iterator stability, and it's pleasant because the `vals` set can just be a regular set.As you say Rust does not allow this; its answer is IndexSet, and it is implemented differently, like:
struct OrderedSet {
Vec<String> buckets;
RawTable<usize> hashToBucketIndex;
}
RawTable is a hash table that doesn't know how to compute a hash or determine equality. Instead, you provide it with closures to do those tasks, but at the call site (not construction time).Basically Rust achieves the same thing through a layer of indirection involving indexes, which is a common pattern.
If you wanted to do the same in Rust it would be Vec<Box<T>>. Mutating the collection won't invalidate the pointers.
auto& r = *some_vector[0];(Though it's still pretty brittle, so you may want to add a ton of comments to warn yourself in the future...)
I'm not going to pretend that I understand everything on that site (particularly anything about complex templates and things like SFINAE) but often there's comprehensible stuff in there. It can be really helpful.
The big issue is that becoming involved in the C++ standardization process is purposely arcane, requiring people to physically travel to remote locations, miss time off work, and spend a lot of money. There are literally substantial language features added to C++ that are nothing more than the work of maybe 3-4 people. These features could have benefited enormously from having 100s, if not 1000s of potential developers exercising use cases and contributing suggestions, but the standardization process is heavily gated.
9/10 times when there is resistance to a particular feature it's because implementing it breaks the ABI.
> requiring people to physically travel to remote locations, miss time off work, and spend a lot of money.
It's a different kind of barrier to entry, but I would be surprised if the attendees of the standards meetings aren't being compensated for it.
1. Backwards compatibility with already existing binaries? 2. Speed speed speed? 3. Ergonomics?
The problem is similar in C as well.
`printf("%d, %d", i++, i++);` will give you different results depending on the compiler.
[0] https://stackoverflow.com/a/7693775/
[1] The final bullet-point in the Notes section of https://en.cppreference.com/w/cpp/memory/shared_ptr/make_sha...
[2] https://stackoverflow.com/questions/38501587/what-are-the-ev...
struct Dummy {
Dummy(int) {}
};
struct World {
World(const Dummy &) {}
void hello() {}
};
int main() {
int value = 42;
World world(Dummy(value)); // fails to compile
// World world(Dummy(42)); // works
world.hello();
return 0;
}In 99.9% of cases, it's just a surprising compiler error message that you learn to avoid. However, there's a related version of this problem which can lead to accidentally declaring a function prototype rather than acquiring a lock. You'll get compiler warnings from -Wshadow, but the seriousness of the problem might not be obvious.
That said, it's a very rare problem these days, due to the introduction of uniform initialization in C++11.
World world(Dummy(value));
Can be interpreted as the following function declaration: World world(Dummy value);
As mentioned in child comment. This is sometimes called the most vexing parse: https://en.wikipedia.org/wiki/Most_vexing_parseIt originates because C++ allows superfluous parentheses around function parameter declarations.
Basically, the lifetime aspects of r/l-values are improperly coupled to the "can I scavenge the internals?" aspect (via const). R-values should not have been promoted to const-ref (I think it was a legacy behavior?) because then this const-ref can be passed around (e.g. returned) as if it were going to outlive the original reference's frame!
This was the first time I realized what a mess C++ can be (although I still use it a lot). This is a subtle error that I have seen seasoned experts miss in code review (especially in templated code). You can't work around it like you can the underperforming parts of the stdlib (Abseil and Folly help out a lot!). This promotion choice of auto&& -> auto const& is really baked into the language and I don't see a path to change it.
The other "biggest foot cannon" has gotta be the incredibly subtle ways one can violate the ABI, e.g. executable A linking against libs B and C, each of which bundle an ABI-incompatible implementation of the same parent dep D (versions 1.1 and 2.1). You never know which type of object you're really passing around with D::SomeType!
[0] https://quuxplusone.github.io/blog/2020/03/04/rvalue-lifetim...
why is it always C++ people that come up with those dramatic-sounding names
Not just clothes can be fashionable; vocabulary, too.
> When a function is called, each parameter ([dcl.fct]) shall be initialized ([dcl.init], [class.copy], [class.ctor]) with its corresponding argument. [ Note: Such initializations are indeterminately sequenced with respect to each other ([intro.execution]) — end note ]
So it's only about initialisation of parameters from arguments, not to the evaluation of arguments. (For example if foo() takes a std::string parameter, and bar() returns a const char*, then in the expression foo(bar()) the above quote refers to the call to the string constructor, not to the call to bar().)
The more relevant part is 5.2.2/8:
> [ Note: The evaluations of the postfix expression and of the argument expressions are all unsequenced relative to one another. All side effects of argument expression evaluations are sequenced before the function is entered (see [intro.execution]). — end note ]
Herb Sutter disagrees. [0] The C++ legalese you've quoted seems decisive, unfortunately Sutter's post doesn't mention it.
See also [1][2].
edit quietbritishjim beat me to it, and with a better informed comment to boot.
[0] https://herbsutter.com/2013/05/29/gotw-89-solution-smart-poi... (ctrl-f for known, and see also the comment thread at the bottom of the page)
That one blew my mind when I found out. You can rip off a chunk of an object by accident... and nothing happens whatsoever. There's no warning from the compiler.
You can stuff a Derived into a std::list<Base>, it'll work just fine, and if Derived happened to say, hold a pointer, it'll happily vanish into the ether.
Besides the amount of confusion that can ensure from this, it means you can have problems if you want to introduce inheritance into a place that didn't have it before.
Especially if it's some sort of external component. You think you're clever inheriting from a framework class and adding some data on top? Nope, the internal structure you don't control doesn't want to cooperate with that plan.
Slicing is a bad name for this phenomenon, because what you've described is what the name implies, but that is not what is happening. The original object is completely unchanged. Nothing was ripped off of it. Constructors create new objects.
You can use clang-tidy to warn / error on that: https://clang.llvm.org/extra/clang-tidy/checks/cppcoreguidel...
What is OpenMW? click link. No info. Oh, FAQ.
> "What is OpenMW?"
"OpenMW is a free, open source, and modern engine which re-implements and extends the 2002 Gamebryo engine for the open-world role-playing game The Elder Scrolls III: Morrowind."
Maybe, just maybe, that shouldn't be a FAQ but right on the main page.
Louis Brandy's Curiously Recurring Bugs at Facebook presentation from CppCon17 has somewhat of the same feeling, though it only covers a few bugs: https://youtu.be/lkgszkPnV8g
i think they should add some template argument to determine if an atomic counter is used or not, exactly for the cases where the shared_ptr object is used exclusively from a single thread; but they didn't do that in the standard.
A reasonable solution in my case could be to use std::weak_ptr<> instead but that wouldn't be useful here.
How so? Do you mean if you do exactly what the article says when initialising the capture variables? Or something lambda specific?
On reflection, I suspect the parent comment was referring to creating circular dependencies using lambdas and std::function.
For example, a class Inner wants allow notifying its owner when events happen, so it has a std::function member variable it uses for the callback function, and a class Outer has an instance of Inner as a member variable. But then passes as a callback:
m_inner.set_callback([self=this->shared_from_this()](Param p){ self->handle_inner(p); });
Now Outer owns Inner (directly) and Inner holds a shared_ptr to Outer, so Outer will never be destroyed (and therefore neither will Inner). A.operator=(B)
Hardly any different that knowing what func(A, B) does.First you need to figure out the types of A and B and their "modifiers" (like const or references) to start figuring out which operator=() could potentially be called. That might still be very hard to do if for example there are implicit conversions from B to some other type involved. Such conversions can depend on code which might be nowhere close to where the operator=() is defined.
Or if we take an Algol derived language, like Pascal or Modula-2, func might have been defined as,
type
my_complex_type = ....
procedure func(var a, b:my_complex_type);
begin
end;
Raising the same kind of questions.Yes there are issues with C++ approach as you describe, however sometimes it seems C++ hate kind of blinds the people that similar issues occur in other languages to some extent.
I understand the practical reasons for it, but it feels very wrong.
I've not encountered a single instance of slicing in 10+ years of C++.
Jesus christ, what an utter mess of a language.
Also some of the C++ horrors are caused by the consequences to stay copy paste compatible with said documents and tooling across all platforms where a C compiler exists.
void frob(std::shared_ptr<T>);
main() {
frob(std::make_unique<T>());
}If something takes a foo, give it a foo.