0

I'd like to ask for your help. I am new in this and I can't get to make MOVE ctor work.

My move CTOR is not getting hit for some reason, I don't understand. Please help me.

#include<iostream>
class DynamicInt
{

public:
DynamicInt()
: intPtr{ new int {0} }
{
}

DynamicInt(int value)
: intPtr{ new int { value } }
{
std::cout << "one parameter ctor" << std::endl;
}

~DynamicInt()
{
delete intPtr;
std::cout << "Destructed." << std::endl;
}

// COPY CTOR
DynamicInt(const DynamicInt& other)
: intPtr{ new int { other.GetValue() } }
{
std::cout << "copy CTOR\n";
}

// MOVE CTOR -->>>> NOT GETTING HIT !!!!! :(
DynamicInt(DynamicInt&& other) noexcept
: intPtr { other.intPtr }
{
std::cout << "move con called. \n";
other.intPtr = nullptr;
}

private:

int* intPtr;
};

DynamicInt ConstructorDynamicInt(int val) 
{
    DynamicInt dInt{ val };

    return dInt;
}

int main()
{
    DynamicInt intCOne = ConstructorDynamicInt(20);// should trigger either MOVE or COPY constructor
    std::cout << intCOne.GetValue() << std::endl;
}
one parameter ctor
20
Destructed.

I've already tried searching in Google. Still wouldn't work. From someone else's setup (saw on video), the same exact code works.

But it hits this CTOR instead:

DynamicInt(int value)
: intPtr{ new int { value } }
{
std::cout << "one parameter ctor" << std::endl;
}
9
  • 3
    the compiler is allowed to optimize away the move Commented Jun 4, 2024 at 1:58
  • Hi @NathanOliver What does that mean ? Is there a way I can force the compiler to use the MOVE ctor I defined ? Actually, it does MOVE ctor is not getting hit but what is is the CTOR which accepts an INT parameter. Commented Jun 4, 2024 at 2:02
  • The optimization is called NRVO. -fno-elide-constructors should turn off the optimization with GCC and Clang Commented Jun 4, 2024 at 2:11
  • Does returning a local variable return a copy and destroy the original(nrvo)? Commented Jun 4, 2024 at 2:22
  • 1
    @user12002570 Thank you so much for the DEMO. I am checking it and will study it. Thank you so much. Commented Jun 4, 2024 at 2:57

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.