Is c++11 enum class thred safe? - c++11

I wonder what happens if I don't lock an enum variable in the following writer-reader situation:
enum class Foo {One,Two,Three};
Foo foo = Foo::One;
// Thread A:
wait_for_something();
// no mutex lock
foo= Foo::Two;
// Thread B:
while(foo==Foo::One){
// no mutex lock
do_something();
}
I can think of sequences that in the middle of do_something, foo changes. This is not really important, I would like to know if there is any other issues with this lockless code?

Related

Casting Parent Struct to Child Struct [duplicate]

In c++ what is object slicing and when does it occur?
"Slicing" is where you assign an object of a derived class to an instance of a base class, thereby losing part of the information - some of it is "sliced" away.
For example,
class A {
int foo;
};
class B : public A {
int bar;
};
So an object of type B has two data members, foo and bar.
Then if you were to write this:
B b;
A a = b;
Then the information in b about member bar is lost in a.
Most answers here fail to explain what the actual problem with slicing is. They only explain the benign cases of slicing, not the treacherous ones. Assume, like the other answers, that you're dealing with two classes A and B, where B derives (publicly) from A.
In this situation, C++ lets you pass an instance of B to A's assignment operator (and also to the copy constructor). This works because an instance of B can be converted to a const A&, which is what assignment operators and copy-constructors expect their arguments to be.
The benign case
B b;
A a = b;
Nothing bad happens there - you asked for an instance of A which is a copy of B, and that's exactly what you get. Sure, a won't contain some of b's members, but how should it? It's an A, after all, not a B, so it hasn't even heard about these members, let alone would be able to store them.
The treacherous case
B b1;
B b2;
A& a_ref = b2;
a_ref = b1;
//b2 now contains a mixture of b1 and b2!
You might think that b2 will be a copy of b1 afterward. But, alas, it's not! If you inspect it, you'll discover that b2 is a Frankensteinian creature, made from some chunks of b1 (the chunks that B inherits from A), and some chunks of b2 (the chunks that only B contains). Ouch!
What happened? Well, C++ by default doesn't treat assignment operators as virtual. Thus, the line a_ref = b1 will call the assignment operator of A, not that of B. This is because, for non-virtual functions, the declared (formally: static) type (which is A&) determines which function is called, as opposed to the actual (formally: dynamic) type (which would be B, since a_ref references an instance of B). Now, A's assignment operator obviously knows only about the members declared in A, so it will copy only those, leaving the members added in B unchanged.
A solution
Assigning only to parts of an object usually makes little sense, yet C++, unfortunately, provides no built-in way to forbid this. You can, however, roll your own. The first step is making the assignment operator virtual. This will guarantee that it's always the actual type's assignment operator which is called, not the declared type's. The second step is to use dynamic_cast to verify that the assigned object has a compatible type. The third step is to do the actual assignment in a (protected!) member assign(), since B's assign() will probably want to use A's assign() to copy A's, members.
class A {
public:
virtual A& operator= (const A& a) {
assign(a);
return *this;
}
protected:
void assign(const A& a) {
// copy members of A from a to this
}
};
class B : public A {
public:
virtual B& operator= (const A& a) {
if (const B* b = dynamic_cast<const B*>(&a))
assign(*b);
else
throw bad_assignment();
return *this;
}
protected:
void assign(const B& b) {
A::assign(b); // Let A's assign() copy members of A from b to this
// copy members of B from b to this
}
};
Note that, for pure convenience, B's operator= covariantly overrides the return type, since it knows that it's returning an instance of B.
If You have a base class A and a derived class B, then You can do the following.
void wantAnA(A myA)
{
// work with myA
}
B derived;
// work with the object "derived"
wantAnA(derived);
Now the method wantAnA needs a copy of derived. However, the object derived cannot be copied completely, as the class B could invent additional member variables which are not in its base class A.
Therefore, to call wantAnA, the compiler will "slice off" all additional members of the derived class. The result might be an object you did not want to create, because
it may be incomplete,
it behaves like an A-object (all special behaviour of the class B is lost).
These are all good answers. I would just like to add an execution example when passing objects by value vs by reference:
#include <iostream>
using namespace std;
// Base class
class A {
public:
A() {}
A(const A& a) {
cout << "'A' copy constructor" << endl;
}
virtual void run() const { cout << "I am an 'A'" << endl; }
};
// Derived class
class B: public A {
public:
B():A() {}
B(const B& a):A(a) {
cout << "'B' copy constructor" << endl;
}
virtual void run() const { cout << "I am a 'B'" << endl; }
};
void g(const A & a) {
a.run();
}
void h(const A a) {
a.run();
}
int main() {
cout << "Call by reference" << endl;
g(B());
cout << endl << "Call by copy" << endl;
h(B());
}
The output is:
Call by reference
I am a 'B'
Call by copy
'A' copy constructor
I am an 'A'
Third match in google for "C++ slicing" gives me this Wikipedia article http://en.wikipedia.org/wiki/Object_slicing and this (heated, but the first few posts define the problem) : http://bytes.com/forum/thread163565.html
So it's when you assign an object of a subclass to the super class. The superclass knows nothing of the additional information in the subclass, and hasn't got room to store it, so the additional information gets "sliced off".
If those links don't give enough info for a "good answer" please edit your question to let us know what more you're looking for.
The slicing problem is serious because it can result in memory corruption, and it is very difficult to guarantee a program does not suffer from it. To design it out of the language, classes that support inheritance should be accessible by reference only (not by value). The D programming language has this property.
Consider class A, and class B derived from A. Memory corruption can happen if the A part has a pointer p, and a B instance that points p to B's additional data. Then, when the additional data gets sliced off, p is pointing to garbage.
In C++, a derived class object can be assigned to a base class object, but the other way is not possible.
class Base { int x, y; };
class Derived : public Base { int z, w; };
int main()
{
Derived d;
Base b = d; // Object Slicing, z and w of d are sliced off
}
Object slicing happens when a derived class object is assigned to a base class object, additional attributes of a derived class object are sliced off to form the base class object.
I see all the answers mention when object slicing happens when data members are sliced. Here I give an example that the methods are not overridden:
class A{
public:
virtual void Say(){
std::cout<<"I am A"<<std::endl;
}
};
class B: public A{
public:
void Say() override{
std::cout<<"I am B"<<std::endl;
}
};
int main(){
B b;
A a1;
A a2=b;
b.Say(); // I am B
a1.Say(); // I am A
a2.Say(); // I am A why???
}
B (object b) is derived from A (object a1 and a2). b and a1, as we expect, call their member function. But from polymorphism viewpoint we don’t expect a2, which is assigned by b, to not be overridden. Basically, a2 only saves A-class part of b and that is object slicing in C++.
To solve this problem, a reference or pointer should be used
A& a2=b;
a2.Say(); // I am B
or
A* a2 = &b;
a2->Say(); // I am B
So ... Why is losing the derived information bad? ... because the author of the derived class may have changed the representation such that slicing off the extra information changes the value being represented by the object. This can happen if the derived class if used to cache a representation that is more efficient for certain operations, but expensive to transform back to the base representation.
Also thought someone should also mention what you should do to avoid slicing...
Get a copy of C++ Coding Standards, 101 rules guidlines, and best practices. Dealing with slicing is #54.
It suggests a somewhat sophisticated pattern to fully deal with the issue: have a protected copy constructor, a protected pure virtual DoClone, and a public Clone with an assert which will tell you if a (further) derived class failed to implement DoClone correctly. (The Clone method makes a proper deep copy of the polymorphic object.)
You can also mark the copy constructor on the base explicit which allows for explicit slicing if it is desired.
The slicing problem in C++ arises from the value semantics of its objects, which remained mostly due to compatibility with C structs. You need to use explicit reference or pointer syntax to achieve "normal" object behavior found in most other languages that do objects, i.e., objects are always passed around by reference.
The short answers is that you slice the object by assigning a derived object to a base object by value, i.e. the remaining object is only a part of the derived object. In order to preserve value semantics, slicing is a reasonable behavior and has its relatively rare uses, which doesn't exist in most other languages. Some people consider it a feature of C++, while many considered it one of the quirks/misfeatures of C++.
1. THE DEFINITION OF SLICING PROBLEM
If D is a derived class of the base class B, then you can assign an object of type Derived to a variable (or parameter) of type Base.
EXAMPLE
class Pet
{
public:
string name;
};
class Dog : public Pet
{
public:
string breed;
};
int main()
{
Dog dog;
Pet pet;
dog.name = "Tommy";
dog.breed = "Kangal Dog";
pet = dog;
cout << pet.breed; //ERROR
Although the above assignment is allowed, the value that is assigned to the variable pet loses its breed field. This is called the slicing problem.
2. HOW TO FIX THE SLICING PROBLEM
To defeat the problem, we use pointers to dynamic variables.
EXAMPLE
Pet *ptrP;
Dog *ptrD;
ptrD = new Dog;
ptrD->name = "Tommy";
ptrD->breed = "Kangal Dog";
ptrP = ptrD;
cout << ((Dog *)ptrP)->breed;
In this case, none of the data members or member functions of the dynamic variable
being pointed to by ptrD (descendant class object) will be lost. In addition, if you need to use functions, the function must be a virtual function.
It seems to me, that slicing isn't so much a problem other than when your own classes and program are poorly architected/designed.
If I pass a subclass object in as a parameter to a method, which takes a parameter of type superclass, I should certainly be aware of that and know the internally, the called method will be working with the superclass (aka baseclass) object only.
It seems to me only the unreasonable expectation that providing a subclass where a baseclass is requested, would somehow result in subclass specific results, would cause slicing to be a problem. Its either poor design in the use of the method or a poor subclass implementation. I'm guessing its usually the result of sacrificing good OOP design in favor of expediency or performance gains.
OK, I'll give it a try after reading many posts explaining object slicing but not how it becomes problematic.
The vicious scenario that can result in memory corruption is the following:
Class provides (accidentally, possibly compiler-generated) assignment on a polymorphic base class.
Client copies and slices an instance of a derived class.
Client calls a virtual member function that accesses the sliced-off state.
Slicing means that the data added by a subclass are discarded when an object of the subclass is passed or returned by value or from a function expecting a base class object.
Explanation:
Consider the following class declaration:
class baseclass
{
...
baseclass & operator =(const baseclass&);
baseclass(const baseclass&);
}
void function( )
{
baseclass obj1=m;
obj1=m;
}
As baseclass copy functions don't know anything about the derived only the base part of the derived is copied. This is commonly referred to as slicing.
class A
{
int x;
};
class B
{
B( ) : x(1), c('a') { }
int x;
char c;
};
int main( )
{
A a;
B b;
a = b; // b.c == 'a' is "sliced" off
return 0;
}
when a derived class object is assigned to a base class object, additional attributes of a derived class object are sliced off (discard) form the base class object.
class Base {
int x;
};
class Derived : public Base {
int z;
};
int main()
{
Derived d;
Base b = d; // Object Slicing, z of d is sliced off
}
When a Derived class Object is assigned to Base class Object, all the members of derived class object is copied to base class object except the members which are not present in the base class. These members are Sliced away by the compiler.
This is called Object Slicing.
Here is an Example:
#include<bits/stdc++.h>
using namespace std;
class Base
{
public:
int a;
int b;
int c;
Base()
{
a=10;
b=20;
c=30;
}
};
class Derived : public Base
{
public:
int d;
int e;
Derived()
{
d=40;
e=50;
}
};
int main()
{
Derived d;
cout<<d.a<<"\n";
cout<<d.b<<"\n";
cout<<d.c<<"\n";
cout<<d.d<<"\n";
cout<<d.e<<"\n";
Base b = d;
cout<<b.a<<"\n";
cout<<b.b<<"\n";
cout<<b.c<<"\n";
cout<<b.d<<"\n";
cout<<b.e<<"\n";
return 0;
}
It will generate:
[Error] 'class Base' has no member named 'd'
[Error] 'class Base' has no member named 'e'
I just ran across the slicing problem and promptly landed here. So let me add my two cents to this.
Let's have an example from "production code" (or something that comes kind of close):
Let's say we have something that dispatches actions. A control center UI for example.
This UI needs to get a list of things that are currently able to be dispatched. So we define a class that contains the dispatch-information. Let's call it Action. So an Action has some member variables. For simplicity we just have 2, being a std::string name and a std::function<void()> f. Then it has an void activate() which just executes the f member.
So the UI gets a std::vector<Action> supplied. Imagine some functions like:
void push_back(Action toAdd);
Now we have established how it looks from the UI's perspective. No problem so far. But some other guy who works on this project suddenly decides that there are specialized actions that need more information in the Action object. For what reason ever. That could also be solved with lambda captures. This example is not taken 1-1 from the code.
So the guy derives from Action to add his own flavour.
He passes an instance of his home-brewed class to the push_back but then the program goes haywire.
So what happened?
As you might have guessed: the object has been sliced.
The extra information from the instance has been lost, and f is now prone to undefined behaviour.
I hope this example brings light about for those people who can't really imagine things when talking about As and Bs being derived in some manner.

c++11 local static member variable destruction order for shared_ptr objects

I've been struggling with a destructor call order which I cannot really understand.
Say we have the following definitions:
#include <memory>
#include <iostream>
class DummyClass {
std::string name;
public:
DummyClass(std::string name) : name(name) { std::cout << "DummyClass(" << name << ")" << std::endl; }
~DummyClass() { std::cout << "~DummyClass(" << name << ")" << std::endl; }
};
class TestClass {
private:
static DummyClass dummy;
static DummyClass& objects() {
static DummyClass dummy("inner");
return dummy;
}
public:
TestClass() {
std::cout << "TestClass" << std::endl;
std::cout << "TestClass Objects is: " << &objects() << std::endl;
}
virtual ~TestClass() {
std::cout << "~TestClass Objects is: " << &objects() << std::endl;
std::cout << "~TestClass" << std::endl;
}
};
DummyClass TestClass::dummy("outer");
Now, If I instantiate the TestClass as follows:
TestClass *mTest = nullptr;
int main() {
mTest = new TestClass(); delete mTest;
return 0;
}
The output obtained is the one I would expect:
DummyClass(outer)
TestClass
DummyClass(inner)
TestClass Objects is: 0x....
~TestClass Objects is: 0x....
~TestClass
~DummyClass(inner)
~DummyClass(outer)
But, now, if I use a shared_ptr for mTest, like:
std::shared_ptr<TestClass> mTest;
int main() {
mTest = std::make_shared<TestClass>();
return 0;
}
the output produced is:
DummyClass(outer)
TestClass
DummyClass(inner)
TestClass Objects is: 0x....
~DummyClass(inner)
~TestClass Objects is: 0x....
~TestClass
~DummyClass(outer)
Can someone explain why is the DummyClass inner object being destroyed before the end of the TestClass object destructor, in this particular case?
I found consistent behavior for gcc 5.2.0 using -std=gnu++11 and clang 3.8.0 with -std=c++11 but could not find any particular documentation citing this example.
Edit: To clarify: all of the code above was written in the same translation unit (*.cpp file) in the presented order. It is a simplification of a usage case where I have a header only class definition which must hold a static list of this pointers to derived class objects. These pointers are added via ctor and removed when the dtor is reached. The problem is triggered when destroying the last object. The list is kept inside a static method and accessed through it to achieve the header only goal.
The rules for all objects with static storage duration (namespace members, static class members, and static objects in function definitions) are:
If the entire initialization can be considered a constant expression, that initialization happens before anything else. (Doesn't apply to anything in your examples.) Otherwise,
Namespace members and static class members are guaranteed to begin initialization at some point before any function in the same translation unit is called. (In most implementations, if we ignore dynamic library loading, all of these happen before main begins. In your examples, since main is in the same TU, we know they happen before main.)
Namespace members and static class members defined in the same TU begin their initializations in the order of their definitions.
For namespace members and static class members defined in different TUs, there is no guarantee on order of initialization!
Static objects defined inside a function begin their initialization the first time program control reaches the definition (if ever).
When main returns or std::exit is called, all objects with static storage duration are destroyed in order opposite to when each completed its initialization.
So in your second example:
Initialization of TestClass::dummy begins. First a temporary std::string is created, and then DummyClass::DummyClass(std::string) is called.
The DummyClass constructor does a std::string copy, then outputs "DummyClass(outer)\n". The temporary std::string is destroyed. Initialization of TestClass::dummy is complete.
Initialization of ::mTest begins. This calls std::shared_ptr<TestClass>::shared_ptr().
The shared_ptr constructor sets up the smart pointer to be null. Initialization of ::mTest is complete.
main begins.
The std::make_shared call ends up creating a TestClass object, calling TestClass::TestClass(). This constructor first prints "TestClass\n", then calls TestClass::objects().
Inside TestClass::objects(), initialization of local object dummy begins. Again a temporary std::string is created, and DummyClass::DummyClass(std::string) is called.
The DummyClass constructor does a std::string copy, then outputs "DummyClass(inner)\n". The temporary std::string is destroyed. Initialization of objects' dummy is complete.
TestClass::TestClass() continues, printing "TestClass Objects is: 0x...\n". Initialization of the dynamic TestClass object is complete.
Back in main, the make_shared function returns a temporary std::shared_ptr<TestClass>. A move assignment moves from the returned temporary to ::mTest, then the temporary is destroyed. Note that although the TestClass object is associated with ::mTest, it has dynamic storage duration, not static storage duration, so the above rules do not apply to it.
main returns. C++ begins destroying objects with static storage duration.
The last static object to finish initialization was the dummy local of TestClass::objects() at step 8 above, so it is destroyed first. Its destructor body outputs "~DummyClass(inner)\n".
The next object to finish initializing was ::mTest in step 4 above, so its destruction begins next. The ~shared_ptr destructor ends up destroying the owned dynamic TestClass object.
The TestClass::~TestClass() destructor body first calls TestClass::objects().
In TestClass::objects(), we encounter the definition of an already destroyed function-local static, which is Undefined Behavior! Apparently though, your implementation does nothing but return a reference to the storage that formerly contained dummy, and it's probably a good thing you didn't do anything with it other than take the address.
TestClass::~TestClass() continues, outputting "~TestClass Objects is: 0x...\n" and then "~TestClass\n".
The ~shared_ptr destructor for ::mTest deallocates associated memory and completes.
Finally, the first static object to finish initialization was TestClass::dummy, in step 2 above, so it is destroyed last. The DummyClass::~DummyClass destructor body outputs "~DummyClass\n". The program is finished.
So the big difference between your two examples is the fact that the TestClass destruction gets delayed until the shared_ptr is destroyed - it doesn't really matter when in the scheme of things the TestClass was created. Since the shared_ptr was created before the "inner" DummyClass in the second example, its destruction happens after the "inner" object is gone, causing that Undefined Behavior.
If this is a simplification of an actual issue you ran into and need to fix, you might try adding something like
class TestClass {
// ...
public:
class ForceInit {
ForceInit() { TestClass::objects(); }
};
// ...
};
// ...
TestClass::ForceInit force_init_before_mTest;
std::shared_ptr<TestClass> mTest;
It's not related to shared_ptr but to the order of destruction of global variables in modules (cc files). The spec states that the order is undefined so you can not assume that static inner object will be destroyed after or before another global object. If you need to have a consistent order of destruction I advise that you take care of it explicitly.

Should we delclare/define destructor even if the class is composed by only smart pointers?

class A{
public:
A():p(nullptr){};
private:
std::unique_ptr<B> p; // B is some class
};
When the object of A goes out of scope, the memory space which consumes for p is automatically removed.
Should we explicitly write the destructor as below?
~A(){
delete p;
}
Is this redundant?
Should we explicitly write the destructor as below?
No. The whole point of smart pointers is that memory is managed automatically for you.
Is this redundant?
No, it's undefined behavior - a "double free" will be performed. Even if you provide a destructor for A, p's destructor will be called regardless.

End of lifetime of static object at block scope versus global scope

In this passage on program exit from cppreference.com
If the completion of the constructor or dynamic initialization for thread-local or static object A was sequenced-before thread-local or static object B, the completion of the destruction of B is sequenced-before the start of the destruction of A
what is the meaning of "sequenced-before"?
In particular, for this program
struct Object {
Object() {
}
~Object() {
}
};
Object a;
void f() {
static Object b;
}
int main() {
f();
}
is it safe to assume that a.~Object() is called after b.~Object() because a.Object() is called before b.Object()?
what is the meaning of "sequenced-before"?
Objects are initialized at run time by the run time environment in a sequence. If initialization of one object comes before initialization of a second object, then the construction of the first object is "sequenced-before" construction of the second object.
is it safe to assume that a.~Object() is called after b.~Object() because a.Object() is called before b.Object()?
If you can assume that a.Object() is called before b.Object(), then you can assume that a.~Object() is called after b.~Object(). However, that is not always the case. In your posted code that is true. But it is possible, in a more complex application, that f() is called before a is initialized.

data members in an OpenMP loop

I have the following class:
Class L{
public:
bool foo(vector<bool> & data);
private:
C** cArray;
}
and would like to parallelize the for loop in the function foo which is called somtime after an object of L is created and all the elements in cArray are initialized.
bool L::foo(vector<int> & data){
int row, col;
#pragma omp parallel shared(SIZE, cArray, data) private(row, col)
for (row=0, row<SIZE; ++row)
{
for (col=0; col<SIZE; ++col)
{
cArray[row][col].computeScore(data);
}
}
}
But this gives an error:
error C3028: 'L::cArray' : only a variable or static data member can be used in a data-sharing clause.
Is there anything that can be done about this assuming I don't want to make cArray static?
This question has come up several times before. The problem is, that class data members may not be instantiated at compile time. If they are being shared, then there is no problem, because variables are shared by default in OpenMP (unless you change the default to private - which you can't do in C - or none). However, if they are defined as private, then the compiler needs to know how to make private copies and this information is not always available at compile time.
Unfortunately, if you want to scope all your data (using explicit data scoping clauses), which you should, then you have a problem. The scoping clauses can only handle variables - which class data members aren't. Leaving them off any data scoping clause works as long as the default remains shared. If you want them to be private, then you are out of luck and need to define the class data members as variables. Unfortunately, since OpenMP is not part of the base language, I don't see this changing anytime soon.
You can use C++ 11 thread_local like following. Then it should all work as intended.
// .h
Class L{
public:
bool foo(vector<bool> & data);
private:
static thread_local C** cArray;
}
// .cpp
thread_local C** cArray;

Resources