Can't get move constructor to run - c++11

C++11
I'm having trouble using the move constructor. I have a simple container class, called Number, whose only data member is an integer. I have the following code:
//Number.h
#ifndef NUMBER_H
#define NUMBER_H
#include <iostream>
class Number
{
public:
Number();
Number(int ipar);
Number(const Number& src);
Number(Number&& src);
private:
int num;
};
#endif
and
//Number.cpp
#include "Number.h"
Number::Number()
{
std::cout << "default ctor" << std::endl;
}
Number::Number(int ipar) : num(ipar)
{
std::cout << "integer argument ctor" << std::endl;
}
Number::Number(const Number& src) : num(src.num)
{
std::cout << "copy ctor" << std::endl;
}
Number::Number(Number&& src) : num(src.num)
{
std::cout << "move ctor" << std::endl;
}
and
//main.cpp
#include "Number.h"
using namespace std;
int main()
{
cout << "Part A:" << endl;
Number n1(1);
cout << "Part B:" << endl;
Number n2(n1);
cout << "Part C:" << endl;
Number n3{Number{n1}};
cout << "Part D:" << endl;
Number n4(Number(n1));
return 0;
}
This outputs:
Part A:
integer argument ctor
Part B:
copy ctor
Part C:
copy ctor
Part D:
Notice there is no output for Part D. The output for Parts A and B are what I expected, but the output for the others aren’t.
I expected this for Parts C and D:
Part C:
copy ctor
move ctor
Part D:
copy ctor
move ctor
Expectation for Part C:
I expected the Number{n1} part of Number n3{Number{n1}} to make a temporary nameless Number object, because there is no name between Number and the opening curly brace, by calling the copy constructor with n1. Then I expected Number n3 to be constructed by calling the move constructor with the temporary object.
Expectation for Part D:
Since this is like Part C, except with parentheses instead of curly braces, I expected this part to behave and output in the same way I expected Part C to.
Question:
Why does the actual output differ from my expectations and what is the correct way to get my desired output?
Note: If you want to compile this in Visual Studio, you need the Visual C++ Compiler November 2012 CTP or later for Visual Studio 2012 in order to support the uniform initialization syntax.

n4 is a function declaration. n3 is caused by copy elision.
Check that here I've enabled -fno-elide-constructors to avoid copy elision. n3 then shows a sequence of copy and move constructors.
There's a commented out line that tries to use n4 as an object. If you uncomment it, you'll see the compiler error telling it's a function instead.
For n4 do not be interpreted as a function declaration you could put extra parentheses around the temporary to prevent it from being viewed as a function parameter: Number n4((Number(n1))). With this and -fno-elide-constructors all you've expected happens.
Note that -fno-elide-constructors is not present as an option in MSVC.

Related

What does unique_ptr<T>::operator= do in terms of deallocation

I'm having troubles understanding fully the assignment operator for unique_ptr. I understand that we can only move them, due to the fact that copy constructor and assignment operators are deleted, but what if
a unique_ptr which contains already an allocation is overwritten by a move operation? Is the content previously stored in the smart pointer free'd?
#include <iostream>
#include <memory>
class A{
public:
A() = default;
virtual void act() const {
std::cout << "act from A" << std::endl;
}
virtual ~A() {
std::cout << "destroyed A" << std::endl;
}
};
class B : public A {
public:
B() : A{} {}
void act() const override {
std::cout << "act from B" << std::endl;
}
~B() override {
std::cout << "destroyed from B " << std::endl;
}
};
int main() {
auto pP{std::make_unique<A>()};
pP->act();
==================== ! =======================
pP = std::make_unique<B>(); // || std::move(std::make_unique<B>())
==================== ! =======================
pP->act();
return 0;
}
When I do
pP = std::make_unique<B>();
does it mean that what was allocated in the first lines for pP (new A()) is destructed automatically?
Or should I opt for:
pP.reset();
pP = std::make_unique<B>();
Yes, see section 20.9.1, paragraph 4 of the C++11 draft standard
Additionally, u can, upon request, transfer ownership to another unique pointer u2. Upon completion of
such a transfer, the following postconditions hold:
u2.p is equal to the pre-transfer u.p,
u.p is equal to nullptr, and
if the pre-transfer u.d maintained state, such state has been transferred to u2.d.
As in the case of a reset, u2 must properly dispose of its pre-transfer owned object via the pre-transfer
associated deleter before the ownership transfer is considered complete
In other words, it's cleaning up after itself upon assignment like you'd expect.
Yes, replacing the content of a smart pointer will release the previously-held resource. You do not need to call reset() explicitly (nor would anyone expect you to).
Just for the sake of this particular example. It seems polymorphism in your example didn't allow you to draw clear conclusions from output:
act from A
destroyed A
act from B
destroyed from B
destroyed A
So let's simplify your example and make it straight to the point:
#include <iostream>
#include <memory>
struct A {
explicit A(int id): id_(id)
{}
~A()
{
std::cout << "destroyed " << id_ << std::endl;
}
int id_;
};
int main() {
std::unique_ptr<A> pP{std::make_unique<A>(1)};
pP = std::make_unique<A>(2);
}
which outputs:
destroyed 1
destroyed 2
Online
I hope this leaves no room for misinterpretation.

C++11 / Non Constructible but Copyable?

I observed that if I explicitly delete only constructor and destructor of a class then the resultant implementation deletes copy constructor & move constructor, but the compiler still makes copy assignment and move assignment operators implicitly available! Which in turn makes assignment possible!
My question is what is the rational of this? What is the use case where this can be used. Following is an example code for reference:
# ifndef MOEGLICH_H_
# define MOEGLICH_H_
# include <cstdint>
class Moeglich final
{
public :
explicit
Moeglich() = delete ;
~Moeglich() = delete ;
/*
// With explicit deletion
Moeglich& operator=(const Moeglich& other) = delete ;
Moeglich(const Moeglich& other) = delete ;
Moeglich&& operator=(Moeglich&& other) = delete ;
Moeglich(Moeglich&& other) = delete ;
*/
static constexpr uint16_t Egal(const uint8_t& var_) noexcept
{
return static_cast< uint16_t > ( var_ ) ;
}
};
# endif
# include <cstdlib>
# include <iostream>
# include <type_traits>
int main(int argc, char* argv[])
{
std::cout << std::boolalpha
<< "Is constructible : " << std::is_constructible<Moeglich>::value << std::endl
<< "Is destructible : " << std::is_destructible<Moeglich>::value << std::endl
<< "Is copy constructible : " << std::is_copy_constructible<Moeglich>::value << std::endl
<< "Is move constructible : " << std::is_move_constructible<Moeglich>::value << std::endl
<< "Is copy assignable : " << std::is_copy_assignable<Moeglich>::value << std::endl
<< "Is move assignable : " << std::is_move_assignable<Moeglich>::value << std::endl
<< "Is assignable : " << std::is_assignable<Moeglich, Moeglich>::value << std::endl
;
/* Following were what I wanted to prevent anyway :
const Moeglich mom {} ;
Moeglich pop {} ;
Moeglich foo {} ;
foo = mom ;
foo = std::move(pop) ;
*/
return EXIT_SUCCESS ;
}
Edit:: I see I have created a lot of confusion by vaguely putting some codes and not mentioning intent. I will never construct this object. All I am interested is accessing
const uint8_t duh { 5 } ;
const uint16_t notEgal { Moeglich::Egal(duh) } ;
Here is what is important for me: Sometimes, I need partial template specialization of functions which is not allowed which can be enabled if I put this function inside a template class.
I have been pointed to a link here, which very clearly lays down the rule. My expectation from the compiler was wrong and my use-case cannot be understood in a special way by the compiler.
Thanks everybody for commenting.
Regards,
Sumit

Visual studio: How to create hyperlink in comments section in c++ code to go to different lines within the code

I need to create a hyper link in my comments section of my c++ code so that , when I click on the link, it should take me to a specific line of the same code base.
That specific line could be in same file or different, but of course the same project.
Is this possible in Visual studio when writing c/c++ code.
For example,
int main()
{
Marks m1(10,20);
Marks m2(30,40);
Marks m3,m4;
//Line 7
std::cout <<m1.get_int_marks()<<std::endl;
std::cout << m1.get_ext_marks() << std::endl;
m3 = m1 + m2;
//Line 14
std::cout << m3.get_int_marks() << std::endl;
std::cout << m3.get_ext_marks() << std::endl;
m4 = m1 - m2;
int x = 10 + 20;
std::cout << m4.get_int_marks() << std::endl;
std::cout << m4.get_ext_marks() << std::endl;
std::cout << x << std::endl;
return 0;
}
In the above code , can I create a hyperlink in the comments, at line 7 to go to line 14.
Used case can be to go to any line of any file in the project.
Thanks in advance.
In case you want a link to method, you can use empty function macro to prevent compiler warnings, privates, etc.
Put pseudo code inside and follow by F12 (Visual Studio) or similar key elsewhere.
Includes are often mandatory for jump to wanted method directly.
#define CALLERS(...)
#include "myClass.h"
#include "myFunctions.h"
CALLERS(myClass::myMethod; function();)

C++ std::unordered_map key custom hashing

I've got the following test.cpp file
#include <string>
#include <functional>
#include <unordered_map>
#include <iostream>
class Mystuff {
public:
std::string key1;
int key2;
public:
Mystuff(std::string _key1, int _key2)
: key1(_key1)
, key2(_key2)
{}
};
namespace std {
template<>
struct hash<Mystuff *> {
size_t operator()(Mystuff * const& any) const {
size_t hashres = std::hash<std::string>()(any->key1);
hashres ^= std::hash<int>()(any->key2);
std::cout << "Hash for find/insert is [" << hashres << "]" << std::endl;
return (hashres);
}
};
}; /* eof namespace std */
typedef std::unordered_map<Mystuff *, Mystuff *>mystuff_map_t;
mystuff_map_t map;
int insert_if_not_there(Mystuff * stuff) {
std::cout << "Trying insert for " << stuff->key1 << std::endl;
if (map.find(stuff) != map.end()) {
std::cout << "It's there already..." << std::endl;
return (-1);
} else {
map[stuff] = stuff;
std::cout << "Worked..." << std::endl;
}
return (0);
}
int main(){
Mystuff first("first", 1);
Mystuff second("second", 2);
Mystuff third("third", 3);
Mystuff third_duplicate("third", 3);
insert_if_not_there(&first);
insert_if_not_there(&second);
insert_if_not_there(&third);
insert_if_not_there(&third_duplicate);
}
You can compile with g++ -o test test.cpp -std=gnu++11.
I don't get what I'm doing wrong with it: the hash keying algorithm is definitely working, but for some reason (which is obviously in the - bad - way I'm doing something), third_duplicate is inserted as well in the map, while I'd wish it wasn't.
What am I doing wrong?
IIRC unordered containers need operator== as well as std::hash. Without it, I'd expect a compilation error. Except that your key is actually MyStuff* - the pointer, not the value.
That means you get the duplicate key stored as a separate item because it's actually not, to unordered_map, a real duplicate - it has a different address, and address equality is how unordered_map is judging equality.
Simple solution - use std::unordered_map<Mystuff,Mystuff> instead. You will need to overload operator== (or there's IIRC some alternative template, similar to std::hash, that you can specialize). You'll also need to change your std::hash to also accept the value rather than the pointer.
Don't over-use pointers in C++, especially not raw pointers. For pass-by-reference, prefer references to pointers (that's a C++-specific meaning of "reference" vs. "pointer"). For containers, the normal default is to use the type directly for content, though there are cases where you might want a pointer (or a smart pointer) instead.
I haven't thoroughly checked your code - there may be more issues than I caught.

why does `vector<int> v{{5,6}};` work? I thought only a single pair {} was allowed?

Given a class A with two constructors, taking initializer_list<int> and initializer_list<initializer_list<int>> respectively, then
A v{5,6};
calls the former, and
A v{{5,6}};
calls the latter, as expected. (clang3.3, apparently gcc behaves differently, see the answers. What does the standard require?)
But if I remove the second constructor, then A v{{5,6}}; still compiles and it uses the first constructor. I didn't expect this.
I thought that A v{5,6} would be the only way to access the initializer_list<int> constructor.
(I discovered this while playing around with std::vector and this question I asked on Reddit, but I created my own class A to be sure that it wasn't just a quirk of the interface for std::vector.)
I think this answer might be relevant.
Yes, this behaviour is intended, according to §13.3.1.7 Initialization
by list-initialization
When objects of non-aggregate class type T are list-initialized (8.5.4), overload resolution selects the constructor in two phases:
— Initially, the candidate functions are the initializer-list constructors (8.5.4) of the class T and the argument list consists of
the initializer list as a single argument.
— If no viable initializer-list constructor is found, overload resolution is performed again, where the candidate functions are all
the constructors of the class T and the argument list consists of the
elements of the initializer list.
In gcc I tried your example. I get this error:
error: call of overloaded 'A(<brace-enclosed initializer list>)' is ambiguous
gcc stops complaining if I use three sets of brace. i.e.:
#include <iostream>
#include <vector>
#include <initializer_list>
struct A {
A (std::initializer_list<int> il) {
std::cout << "First." << std::endl;
}
A (std::initializer_list<std::initializer_list<int>> il) {
std::cout << "Second." << std::endl;
}
};
int main()
{
A a{0}; // first
A a{{0}}; // compile error
A a2{{{0}}}; // second
A a3{{{{0}}}}; // second
}
In an attempt to mirror the vector's constructors, here are my results:
#include <iostream>
#include <vector>
#include <initializer_list>
struct A {
A (std::initializer_list<int> il) {
std::cout << "First." << std::endl;
}
explicit A (std::size_t n) {
std::cout << "Second." << std::endl;
}
A (std::size_t n, const int& val) {
std::cout << "Third." << std::endl;
}
A (const A& x) {
std::cout << "Fourth." << std::endl;
}
};
int main()
{
A a{0};
A a2{{0}};
A a3{1,2,3,4};
A a4{{1,2,3,4}};
A a5({1,2,3,4});
A a6(0);
A a7(0, 1);
A a8{0, 1};
}
main.cpp:23:10: warning: braces around scalar initializer
A a2{{0}};
^~~
1 warning generated.
First.
First.
First.
First.
First.
Second.
Third.
First.

Resources